2016-09-19 87 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

相關問題