Skip to main content
 首页 » 编程设计

c#之LINQ to Lookup 具有不同的项目和计数

2024年02月20日12lautakyan007

如果我将列表定义为

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());