peter
peter

Reputation: 8662

how to check if key exists before adding in to dictionary

I am adding values in to the dictionary by using following linq code, right now what happens is duplicate key entry comes it is skipping both entries from dictionary, I need at least one to be present in dictionary. How to do it in the following LINQ code. I want it in LINQ only, code is as shown below:

dict = (from x in sites
        let pp1 = x.Split(',')
         where pp1.Length > 2
         let rnc = pp1[1].Replace("work=", "")
         let ems = pp1[2].Replace("Context=", "")
         let pp2 = GetName(ems, "CC", "U").Split('_')
         where pp2.Length > 1 && !ems.Contains("_L_")
         select new
         {
             name_ms = ems,
             Key = ems + "," + rnc,
             Value = Getidname(GetName(ems, "CC", "U"),
             GetCode(pp2[1])) + "," + ems.Split('_')[1]
         })
        .ToDictionary(x => x.Key, x => x.Value);

Upvotes: 4

Views: 3300

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062770

Frankly, I would wite a custom extension method to replace ToDictionary, but instead of using Add, using the indexer assignment:

public static Dictionary<TKey, TValue> ToDictionaryLast<TSource, TKey, TValue>(
    this IEnumerable<TSource> source, Func<TSource, TKey> keySelector,
    Func<TSource, TValue> valueSelector)
{
    var result = new Dictionary<TKey, TValue>();
    foreach(var value in source)
        result[keySelector(value)] = valueSelector(value);
    return result;
}

which - in the case of duplicate keys - retains the last value, rather than failing. Then replace the last operation with:

.ToDictionaryLast(x => x.Key, x => x.Value);

Upvotes: 7

Tomas Chabada
Tomas Chabada

Reputation: 3019

You need to group it by Key property and then Select First from grouped subitems. Then you will effectively skip records not being the first one in grouping by Key.

...).GroupBy(i => i.Key).Select(g => g.First()).ToDictionary(...

Upvotes: 3

Related Questions