2014-09-23 56 views
-5

我想寫使用LINQ查詢它通過字典的關鍵,使組,找到細分電子郵件鍵的值總和爲零GROUP BY列表鍵並找到字典值總結零

List<Tuple<string, int>> refe = new List<Tuple<string, int>>(); 
      refe.Add("aa", 100); 
      refe.Add("aa", -100); 
      refe.Add("bb", 10); 
      refe.Add("bb", -10); 
      refe.Add("cc", 29); 
      refe.Add("dd", 49); 

將導致 「AA」, 「bb」

+2

沒有不possiblr在字典中添加兩次一些關鍵你需要查找相反http://msdn.microsoft.com/en-us/library/ vstudio/bb460184(v = vs.100).aspx – 2014-09-23 11:42:36

+0

您需要考慮使用與@KB不同的數據結構指出,不能在字典中有重複的鍵。也許是'List >'? – DGibbs 2014-09-23 11:44:01

+0

對不起,我意識到你的評論後,我解決了我的問題 – altandogan 2014-09-23 11:44:38

回答

1

你是個幸運的人。 ;-)

我今天早上寫了這個片斷

public static List<T> ToDictionaryCount<T>(this List<Tuple<T, int>> list) 
{ 
    if (list == null) 
     throw new ArgumentNullException("list"); 

    var result = list 
     .GroupBy(tuple => tuple.Item1) 
     .Where(g => g.Sum(tuple => tuple.Item2) == 0) 
     .Select(tuples => tuples.Key) 
     .ToList();; 

    return result; 
} 

希望這有助於你。

編輯:謝謝你的言論詹姆斯;-)

+0

嗯,他沒有那麼幸運,因爲他使用'List >'不是一本字典。 – James 2014-09-23 12:08:56

+0

refe.ToDictionary(x => x.Item1,x => x.Item2); – 2014-09-23 12:19:15

+0

當沒有'Dictionary' - 'refe.GroupBy(x => x.Key).Where(g => g.Sum(x => x.Value)== 0)時,似乎有很多工作要做).Select(x => x.Key)' – James 2014-09-23 12:31:36