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

2 c# c#-4.0

如果我将列表定义为

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>();
Run Code Online (Sandbox Code Playgroud)

我试图在查找中获得结构的不同计数,结构为键,结构计数为值。

目前我有

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

但这只是将数据作为匿名类型返回。有人可以帮助我使用语法将其放入查找中.ToLookup吗?

Jon*_*eet 7

怀疑你真的想要:

var lookup = _itemsList.ToLookup(p => p.Structure);
Run Code Online (Sandbox Code Playgroud)

您仍然可以计算任何组的项目:

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

...但您也获得了每个组中的

如果你真的只想要计数,那么听起来你根本不需要查找 - 你想要一个Dictionary,你可以得到:

var dictionary = _itemsList.GroupBy(p => p.Structure)
                           .ToDictionary(g => g.Key, g => g.Count());
Run Code Online (Sandbox Code Playgroud)