2012-10-17 58 views
1

如果我定義了一個列表,LINQ到查找具有鮮明的項目和數量

public class ItemsList 
{ 
    public string structure { get; set; } 
    public string Unit { get; set; } 
    public double Dim { get; set; } 
    public double Amount { get; set; } 
    public int Order { get; set; } 
    public string Element { get; set; } 
} 

List<ItemsList> _itemsList = new List<ItemsList>(); 

我試圖讓結構的重複計數的查找與結構,爲結構的關鍵和計數值。

目前,我有

var sCount = from p in _itemsList 
    group p by p.Structure into g 
    select new { Structure = g.Key, Count = g.Count() }; 

但這只是返回的數據作爲一個匿名類型。有人可以幫助我的語法使用.ToLookup進入查找?

+0

目前還不清楚是什麼你意思是 - 查找每個鍵有多個值*。這就是它的重點。 –

回答

3

嫌疑你真的想:

var lookup = _itemsList.ToLookup(p => p.Structure); 

,您仍然可以指望任何組的項目:

foreach (var group in lookup) 
{ 
    Console.WriteLine("{0}: {1}", group.Key, group.Count()); 
} 

...但你也有內每組。

如果你真的只想計數,那麼它聽起來就像你不想要查找的話 - 你想Dictionary,您可以得到:

var dictionary = _itemsList.GroupBy(p => p.Structure) 
          .ToDictionary(g => g.Key, g => g.Count());