0

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.

1
  • 2
    Can you provide the code that you had tried and didn't work? This gives a foundation to start from in order to help why it's not working Commented Jan 3, 2023 at 2:32

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

This will be ordered by the occurrence of the "key" while creating the Dictionary and not by the total count descending - e.g, black, red, green, blue and not green, red, black, blue as desired by the op.
Sorry, I forgot that part
Almost there! The ordering needs to be on the "Count" and not the "Key" - also, it's not explicitly required to use ToDictionary based on the original question, omitting it will also give the assumed desired result. It might also be worth providing additional color commentary on why this solution works as a learning exercise for the op given current troubles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.