Home > Mobile >  Group and Count Duplicate values in C# List<string>?
Group and Count Duplicate values in C# List<string>?

Time:01-03

Let's say I have a list of strings like this:

List<string> myList = ["black", "red", "green", "green", "red", "green", "blue"]

I want the return to be group by the string and the count to be how many times it appears in the array, ordered by count:

{
  "green": 3 (because there's 3 "greens" in the list
  "red": 2
  "black" : 1,
  "blue" : 1
}

How can I achieve this with LINQ? I've tried groupby's with count's but I'm not getting the right syntax.

CodePudding user response:

First you need to fix your list initialize to

List<string> input = new List<string> { "black", "red", "green", "green", "red", "green", "blue" };

Then you can use below to get a Dictionary which Key is the color and the Value is counts.

var result = input.GroupBy(x => x).Select(y => new
{
    y.Key,
    Count = y.Count()
}).OrderByDescending(x => x.Count).ToDictionary(z => z.Key, z => z.Count);
  • Related