Is there an alternative to Dictionary/SortedList that allows duplicates? [duplicate]

和自甴很熟 提交于 2019-11-29 13:22:58

If you're using .NET 3.5 then Lookup is probably what you're after.

.NET 2.0: PowerCollections contains the OrderedMultiDictionary.

You still can use SortedList and try to make a unique key by combining your value and a Guid into a class. In this case, you must implement the IComparer<NewKey> for your new key, something like:

class MyKey
{
    public Guid Guid { get; set; }
    public float Value { get; set; }
}

class MyComparer : IComparer<MyKey>
{

    public int Compare(MyKey x, MyKey y)
    {
        if (x == null || y == null)
            throw new InvalidOperationException("both of parameters must be not null");
        if (x.Value < y.Value) return -1;
        if (x.Value > y.Value) return 1;
        return 0;
    }
}

and then

var mySortedList = new SortedList<MyKey, MyValue>(new MyComparer());

Not in the Fx < 3.5.. You can implement one, obviously, with a Dictionary of IList objects. But then you have the encapsulation issue/responsibility.

If you're using .NET 3.5, use the Lookup class.

B08AH

That does not work. As soon as you return 0 from the comparer, it will throw "duplicate" exception.

You don't need classes encapsulation or anything, just make a comparer that does not return 0 (equal) result. Here is an example for int type of key

class MyComparer : IComparer<int>
{

  public int Compare(int x, int y)
  {
    if (x < y)
      return -1;
    else return 1;
  }
}

I came across with same issue.. I needed a sortedList which can allow Duplicate Keys..

var sortList = new SortedList<string, IDictionary<string, object>>();

but this didnt work.. so i used

var list = new List<KeyValuePair<string, IDictionary<string, object>>>();

add new data to it as ..

list.Add(new KeyValuePair<string, IDictionary<string, object>>>(value, Dictionary));

with linq i sorted it with no problem..

Try List<KeyValuePair<TKey, List<TValue>>>();

By definition, a Dictionary contains unique keys. Your example above is effectively a sort of two-dimensional keyed array, a structure I've used many times. Why would you want to have duplicate keys? If you did, how would the Dictionary uniquely address its members?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!