[英]LINQ to Lookup with distinct items and count
如果我將列表定義為
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>();
我試圖在Lookup中獲得一個獨特的結構計數,其中結構為關鍵,結構計數為值。
目前我有
var sCount = from p in _itemsList
group p by p.Structure into g
select new { Structure = g.Key, Count = g.Count() };
但這只是將數據作為匿名類型返回。 有人可以幫助我使用.ToLookup
將其轉換為Lookup的語法嗎?
我懷疑你真的想要:
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.