简体   繁体   English

从列表中获取出现的次数和字符串 <string> 在C#中

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

I have a List<string> where some of the values are repeating. 我有一个List<string> ,其中某些值在重复。 I want to get the particular string and it's number of occurrence. 我想获取特定的string及其出现的次数。 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. 我不确定我在这里缺少什么。

You mixed Key and Value of your dictionary. 您混合了字典的KeyValue You are trying to use Count as key . 您正在尝试使用Count作为

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. 您的最后一个示例有效,因为1发生了一次, 2发生了两次, 3发生了3次,所以没有按键冲突。 Your first example should therefor work, too, but I guess you just didn't show the correct test values in your question. 您的第一个示例也应该为此工作,但是我想您只是没有在问题中显示正确的测试值。

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM