简体   繁体   English

如何在C#中计算列表上相同值的数量

[英]How can I count the number of the same value on list in c#

Here's the code: 这是代码:

List<string> Listahan = new List<string>();
Listahan.Add("TEST1");
Listahan.Add("TEST2");
Listahan.Add("TEST3");
Listahan.Add("TEST4");
Listahan.Add("TEST5");
Listahan.Add("TEST5");
Listahan.Add("TEST1");

Then what I want is when I enter TEST1 on my textbox it will output it's count which is 2. Thank in advance. 然后我想要的是,当我在文本框中输入TEST1时,它将输出计数为2。

string textboxVal = "TEST1";    
int testOccurence = Listahan.Count(str => str == textboxVal);

If you are using .NET 2.0 and don't use LINQBridge : 如果您使用的是.NET 2.0 ,而不使用LINQBridge

int testOccurence = Listahan.FindAll(delegate (string str) { return str == textboxVal;})
                            .Count;

some notes: it might be the case, that you may also need case insensitive search. 一些注意事项:可能是这样,您可能还需要不区分大小写的搜索。 For example user can enter "test1" and receive meaningful results. 例如,用户可以输入"test1"并接收有意义的结果。 You can use next code to achieve this: 您可以使用下一个代码来实现:

Listahan.Count(str => string.Equals(str, textboxVal, StringComparison.OrdinalIgnoreCase))

You also can use GroupBy to count all the text first if you often access: 如果您经常访问,还可以使用GroupBy首先计算所有文本:

var dic = Listahan.GroupBy(x => x)
                  .ToDictionary(g => g.Key, g => g.Count());

int count = dic["TEST1"]; //count of 'TEST1'

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

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