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

拥有回忆 提交于 2019-11-28 06:59:19

问题


Possible Duplicate:
C# Sortable collection which allows duplicate keys

Basically I'd like to make a Dictionary work with duplicate keys without going into custom comparer implementations. There is an idea of:

  Dictionary<key, List<value>>

but it still has some overhead. I wish Dictionary had "AllowDuplicates".


回答1:


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




回答2:


.NET 2.0: PowerCollections contains the OrderedMultiDictionary.




回答3:


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());



回答4:


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.




回答5:


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;
  }
}



回答6:


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>>>();




回答7:


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?



来源:https://stackoverflow.com/questions/551901/is-there-an-alternative-to-dictionary-sortedlist-that-allows-duplicates

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