2011-09-22 148 views
0

匹配字典值我有一个复合字典和一个列表C#LINQ只保留基于列表

Dictionary<Point, List<int>> GroupedIndex 
int[] TobeMatched 

现在我要检查每一个关键,是否还有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 

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

+2

你卡在哪里? – V4Vendetta

回答

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); 

See it in action

+0

太棒了!丹尼尔说,这很有效。 – Suresh

+0

你好乔恩,我正在使用上面的代码,如果数据集大约10,000计数,但对于相当大的数据集,Systemoutofmemory异常已被抛出。任何其他方式我可以实现这一目标? – Suresh

+0

@Suresh:是的:重写你的程序不要尝试一次将所有数据放入内存中。 – Jon