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".
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.
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?
来源:https://stackoverflow.com/questions/551901/is-there-an-alternative-to-dictionary-sortedlist-that-allows-duplicates