vb.net 如何计算列表中的字符串出现次数(字符串)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14987663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:26:00  来源:igfitidea点击:

How to count string occurences in a list(Of String)

vb.net

提问by Jason Bayldon

I am looking to dynamically count from a list, how many times items have occured. I can do it below if I specify the value I am looking for, but what I am really looking to do is to iterate through my list, count occurences, and total them out. My current code is below:

我希望从列表中动态计算项目出现的次数。如果我指定了我要查找的值,我可以在下面执行此操作,但我真正想做的是遍历我的列表,计算出现次数并将它们总计。我目前的代码如下:

Dim itemlist As New List(Of String)
itemlist.add("VALUE1")
itemlist.add("VALUE2")
itemlist.add("VALUE3")


    Dim count As Integer = 0

    For Each value In itemlist

        If value.Equals("VALUE1") Then count += 1

    Next

 Msgbox(count.tostring)

So my point would be instead of searching for the value, let the app total them up and display the counted occurences it to the user, similar to a "COUNTIF" in excel. I cant find much on this without using LINQ, Thanks

所以我的观点不是搜索值,而是让应用程序将它们合计起来并向用户显示计数的出现次数,类似于 Excel 中的“COUNTIF”。如果不使用 LINQ,我就找不到太多关于此的信息,谢谢

回答by Meta-Knight

You can do this very easily with LINQ:

你可以用 LINQ 很容易地做到这一点:

Msgbox(itemlist.Where(Function(value) value = "VALUE1").Count)

To count duplicates, once again it's easy with LINQ:

要计算重复项,再次使用 LINQ 很容易:

Dim itemlist As New List(Of String)
itemlist.Add("RED")
itemlist.Add("RED")
itemlist.Add("RED")
itemlist.Add("GREEN")

dim groups = itemList.GroupBy(Function(value) value)

For Each grp In groups
    Console.WriteLine(grp(0) & " - " & grp.Count )
Next

Output:

输出:

RED - 3
GREEN - 1