Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 473
peter Avatar asked Dec 23 '22 07:12

peter


1 Answers

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);
like image 153
Marc Gravell Avatar answered Dec 25 '22 19:12

Marc Gravell