2011-09-22 149 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