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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With