2011-05-12 79 views
1

我有一個班級。按字段對列表進行分組並將項添加到字典

public class Compaints 
{ 
    public string CustomerNumber{get; set;}, 

    public string Complaint{get; set} 
} 

我有一個投訴列表。我需要按customerNumber進行分組並將其添加到字典中,例如類型 Dictionary<string, int> - 字符串將是客戶編號,int將被計數。

如何在linq中做到這一點?

謝謝。

+0

LINQ's no silver bullet。你可以用一個簡單的FOR循環來完成它,同時你花費在詢問... – 2011-05-12 06:10:31

+0

是的,但是使用LINQ會使代碼變得更清潔? – Lamps 2011-05-12 06:13:52

回答

5
var countByCustomer = complaints.GroupBy(row => row.CustomerNumber) 
    .ToDictionary(grp => grp.Key, grp => grp.Count()); 
+0

謝謝Marc :) – Lamps 2011-05-12 06:22:04

相關問題