GThree
GThree

Reputation: 3502

Get the number of occurance and string from List<string> in C#

I have a List<string> where some of the values are repeating. I want to get the particular string and it's number of occurrence. I tried couple of scenarios where it works and in one particular it doesn't and want to understand why?

Code:

var list  = new List<string>() { "Yahoo" , "MSN", "Yahoo", "MSN", "Yahoo", "MSN", "MSN" };

//Works:
var lineWithNumberOfOccurance = linesFromTextFile.GroupBy(word => word).Select(g => new {Count = g.Count(), g.Key});

//Doesn't work:
var lineWithNumberOfOccurance = linesFromTextFile.GroupBy(x => x).ToDictionary(x => x.Count(), x => x.Key);

Error:

An item with the same key has already been added.

However, Following works fine.

var list = new List<int>() {1, 2, 2, 3, 3, 3};
var test = list.GroupBy(x => x).ToDictionary(x => x.Count(), x => x.Key);

I am not sure what I am missing here.

Upvotes: 1

Views: 68

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

You mixed Key and Value of your dictionary. You are trying to use Count as key.

So if two different words occur the same number of times, you have the same key for two words. Just change the line to

var lineWithNumberOfOccurance = linesFromTextFile.GroupBy(x => x)
              .ToDictionary(x => x.Key, x => x.Count());

Your last example works because 1 occurs one time, 2 occurs two times and 3 occurs three times, so there is no key collision. Your first example should therefor work, too, but I guess you just didn't show the correct test values in your question.

Upvotes: 3

Charles Mager
Charles Mager

Reputation: 26213

They key in a dictionary must be unique. You're using the count as the key, so if you have 2 words that both appear the same number of times then you'll get an exception.

You should use the word as the key given you already know that's unique.

linesFromTextFile.GroupBy(x => x)
    .ToDictionary(x => x.Key, x => x.Count());

Upvotes: 2

Related Questions