Reputation: 3502
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
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
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