c# linq keep only matching dictionary values based on list
I have one composite dictionary and one list
Dictionary<Point, List<int>> GroupedIndex
int[] TobeMatched
Now I want to check for every key, whether there are any matching values in the TobeMatched array. If it is matching, then keep only matching values for that key and remove other values. If there is no match, then delete the key.
Example:
GroupedIndex: [0] -> Key [X=1;Y=1]; Values [0] -> 5, [1] -> 10
[1] -> Key [X=1;Y=2]; Values [0] -> 1, [1] -> 3, [2] -> 6
TobeMatched: {1,2,6}
Result expected:
New dict开发者_如何学运维ionary: [0] -> Key[X=1;Y=2]; Values [0] -> 1, [1] -> 6
is it possible to achieve this in linq?
It's not possible to modify your original dictionary with LINQ, because LINQ is composed of pure operations (i.e. does not mutate the values it works on).
With pure LINQ it is possible to simply get a new dictionary with your specifications:
var newGroupedIndex = GroupedIndex
.Select(pair => new {
Key = pair.Key,
Matched = pair.Value.Intersect(TobeMatched).ToList()
})
.Where(o => o.Matched.Count != 0)
.ToDictionary(o => o.Key, o => o.Matched);
See it in action.
精彩评论