简体   繁体   中英

LINQ to Lookup with distinct items and count

If I define a list as

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

I'm trying to get the a distinct count of structures in a Lookup with structure as the key and count of structure as the value.

At the moment I have

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

but this just returns the data as an anonymous type. Can someone please help me with the syntax to get this into a Lookup using .ToLookup ?

I suspect you actually want:

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

You can still count the items for any group:

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

... but you've also got the values within each group.

If you really just want the count, then it sounds like you don't want a lookup at all - you want a Dictionary , which you can get with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM