c#linq仅保留基于列表的字典值匹配

Sur*_*esh 0 c# linq

我有一个复合词典和一个列表

Dictionary<Point, List<int>> GroupedIndex
int[] TobeMatched
Run Code Online (Sandbox Code Playgroud)

现在我想检查每个键,TobeMatched数组中是否有任何匹配的值.如果匹配,则仅保留该键的匹配值并删除其他值.如果没有匹配项,则删除密钥.

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 dictionary: [0] -> Key[X=1;Y=2]; Values [0] -> 1, [1] -> 6
Run Code Online (Sandbox Code Playgroud)

是否有可能在linq中实现这一目标?

Jon*_*Jon 5

使用LINQ修改原始字典是不可能的,因为LINQ由纯操作组成(即不会改变它所处理的值).

使用纯LINQ,可以简单地获得符合您规范的新字典:

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);
Run Code Online (Sandbox Code Playgroud)

看到它在行动.