C# Linq .ToDictionary() Key Already Exists

旧时模样 提交于 2019-11-30 09:55:40

This just means that when you convert to a Dictionary --

.ToDictionary(itm => itm.Section, itm => itm.kvps);

-- there are multiple keys (itm.Section). You can use ToLookup instead, which is kind of like a dictionary but allows multiple keys.

Edit

There are a couple of ways to call ToLookup. The simplest is to specify the key selector:

var lookup = 
   // ...
.ToLookup(itm => itm.Section);

This should provide a lookup where the key is of type Group. Getting a lookup value should then return an IEnumerable, where T is the anonymous type:

Group g = null;
// TODO get group
var lookupvalues = lookup[g];

If the .NET compiler doesn't like this (sometimes it seems to have trouble figuring out what the various types should be), you can also specify an element selector, for example:

ILookup<string, KeyValuePair<string,string>> lookup = 
    // ...
.ToLookup(
    itm => itm.Section.Value,    // key selector
    itm => itm.kvps              // element selector
);

You can write your own ToDictionary method that doesn't break with duplicate keys easy enough.

public static Dictionary<K,V> ToDictionary<TSource, K, V>(
    this IEnumerable<TSource> source, 
    Func<TSource, K> keySelector, 
    Funct<TSource, V> valueSelector)
{
  //TODO validate inputs for null arguments.

  Dictionary<K,V> output = new Dictionary<K,V>();
  foreach(TSource item in source)
  {
    //overwrites previous values
    output[keySelector(item)] = valueSelector(item); 

    //ignores future duplicates, comment above and 
    //uncomment below to change behavior
    //K key = keySelector(item);
    //if(!output.ContainsKey(key))
    //{
      //output.Add(key, valueSelector(item));
    //}
  }

  return output;
}

I assume that you could figure out how to implement the additional overloads (without value the selector).

Amit Kumar

You can use Tuple to pass multiple keys. Check sample code below:

.ToDictionary(k => new Tuple<string,string>(k.key1,k.key2), v => v.value)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!