Building a dictionary of counts of items in a list

后端 未结 5 1379
广开言路
广开言路 2021-01-02 06:08

I have a List containing a bunch of strings that can occur more than once. I would like to take this list and build a dictionary of the list items as the key and the count

5条回答
  •  鱼传尺愫
    2021-01-02 07:05

    You can use the group clause in C# to do this.

    List stuff = new List();
    ...
    
    var groups = 
        from s in stuff
        group s by s into g
        select new { 
            Stuff = g.Key, 
            Count = g.Count() 
        };
    

    You can call the extension methods directly as well if you want:

    var groups = stuff
        .GroupBy(s => s)
        .Select(s => new { 
            Stuff = s.Key, 
            Count = s.Count() 
        });
    

    From here it's a short hop to place it into a Dictionary:

    var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);
    

提交回复
热议问题