2016-09-19 35 views
0

我需要从列表中找到唯一值以及每个值在原始列表中出现的次数。以下是我迄今为止:列表中每个唯一值的计数

Dim Lister As New List(Of String)() 

For Each item In eColumn 
    Lister.Add(item.value) 
Next 

Dim Result As New List(Of String) 
Result = Lister.Distinct().ToList 

For Each st In Result 
    MsgBox(st) 
Next 

结果是所有的唯一值的列表,但不包括每个项目的计数。例如,如果我的名单是

John 
John 
Abbey 
Larry 
Larry 
Larry 
Charles 

我想4个值返回:约翰= 2,修道院= 1,拉里= 3,查尔斯= 1

+0

[它确实](HTTPS: //msdn.microsoft.com/en-us/library/27b47ht3(v=vs.110).aspx)。 – GSerg

+0

@GSerg请详细解释 – Chrisetiquette

+1

这与Excel有什么关系? –

回答

1

使用LINQ的.Distinct()只会给你一个列表,其中包含你列表中的每个不同的名字;所以当你的消息框循环运行时,你一定已经看到了它,它只显示了你列表中的每个名字一次。

VB的列表没有本地函数来返回列表中出现的项目的计数,所以为了实现您想要的结果,只需使用linq的.GroupBy()函数对它们进行分组。它会返回一个Linq.GroupedEnumerable对象,可以通过迭代,并且还有你要找的那种计数属性:

Dim myList As New List(Of String) From {"John", "John", "Abbey", "Larry", "Larry", "Larry", "Charles"} 

    Dim groupedNames = myList.GroupBy(Function(x) x) 
    If groupedNames IsNot Nothing AndAlso groupedNames.Count > 0 Then 
     For Each person In groupedNames 
      Debug.Print(person.Key & "-" & person.Count.ToString) 
     Next 
    End If 

输出:

John-2 
Abbey-1 
Larry-3 
Charles-1 
+0

你能解释OP在哪里有问题吗?发布解决方案并不能解释为什么他们的代码不起作用是没有用的。 – Codexer

相关问题