Let's say I have this Dictionary:
var Dict = Dictionary<Obj, Value>
And I want to create a new one that is:
var Dict2 = Dictionary<Obj.ParentId, Value>
However, there might be objects that have the same ParentId
, so that would be a problem when creating a new Dictionary. Any two entries with the same ParentId
will have the same Value, so I only care to keep one of the entries. Is there a way to easily do this either through LINQ?
CodePudding user response:
The easiest way to do this is probably imperatively using a loop. In this approach, the last one wins - but, as you say, this shouldn't matter in your case:
var dict2 = new Dictionary<Obj.ParentId, Value>();
foreach (var (key, value) in dict1)
{
dict2[key.ParentId] = value;
}
You could also do this using LINQ, but it's probably less performant given it has to do the 'distinct' part first:
var dict2 = dict1
.DistinctBy(x => x.Key.ParentId)
.ToDictionary(x => x.Key.ParentId, x => x.Value);
CodePudding user response:
You can use Linq: query Dict
and materialize result as Dict2
var Dict2 = Dict
.GroupBy(pair => pair.Key.ParentId, pair => pair.Value)
// Or group.Last().Value or some other logic
.ToDictionary(group => group.Key, group => group.First().Value);
Or you can try looping:
var Dict2 = Dictionary<Obj.ParentId, Value>();
foreach (var pair in Dict)
Dict2.TryAdd(pair.Key.ParentId, pair.Value);