Building a dictionary of counts of items in a list

后端 未结 5 1403
广开言路
广开言路 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 06:48

    Dictionary a = stuff.GroupBy(p => p).OrderByDescending(r=>r.Count()).ToDictionary(q => q.Key, q => q.Count());
    

    You can GroupBy and then create dictionary to count each group. As performance test indicate, usually there are more efficient approaches other than Linq. I think your code is more efficient, while Linq solution is more readable and beautiful.

提交回复
热议问题