2016-09-20 68 views
-2

我有一個名稱列表,我需要計算名稱在該列中出現的次數。我正在嘗試使用LINQ,但我不完全理解下面發生的事情的語法。需要通過vb.net獲得列中每個不同值的計數

Dim xlApp As Excel.Application 
    Dim xlWorkBook As Excel.Workbook 
    Dim xlWorkSheet As Excel.Worksheet 
    Dim misValue As Object = System.Reflection.Missing.Value 

    xlApp = New Excel.Application 
    xlWorkBook = xlApp.Workbooks.Add("C:\WORK\TestFile.xlsx") 
    xlWorkSheet = xlWorkBook.Sheets("sheet1") 

    Dim AddCol As Excel.Range = xlWorkSheet.Range("b2") 
    Dim lastRow As Integer = AddCol.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row 
    Dim Lastof As String = ("b2:" & "b" & lastRow & """").Replace("""", "") 
    Dim excelColumn As Excel.Range = xlWorkSheet.Range(Lastof) 
    'MsgBox(Lastof) 

    Dim Lister As New List(Of String)() 

    For Each Names In excelColumn 
     Lister.Add(Names.value) 

    Next 

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


    For Each uniqueItem In Result 

     Dim myList As New List(Of String) From {uniqueItem} 
     Dim groupedNames = myList.GroupBy(Function(x) x) 
     If groupedNames IsNot Nothing AndAlso groupedNames.Count > 0 Then 
      Dim msg As String = Nothing 
      For Each person In groupedNames 
       msg += person.Key & "-" & person.Count.ToString & vbCrLf 
      Next 
      MsgBox(msg) 
     End If 


    Next 
+2

這是非常接近你的前一個問題......你需要放棄你「對於每個uniqueItem」迭代,只是直行進入GroupedNames邏輯使用「Lister.GroupBy」 – soohoonigan

+0

@soohoonigan謝謝!這很好用!我無法評論你對我發表的其他帖子的回答。我將確保刪除該帖子。 – Chrisetiquette

+1

我並不是說你需要刪除它,我只是說如果你需要對答案作出澄清,你總是可以在它下面的評論中提出要求,而不是發佈一個新問題。很高興你的工作雖然 – soohoonigan

回答

0

這是什麼結束了爲我工作。我從上面的代碼中刪除了「For Each uniqueItem」,它完美地工作。

Dim groupedNames = Lister.GroupBy(Function(x) x) 
     If groupedNames IsNot Nothing AndAlso groupedNames.Count > 0 Then 
      Dim msg As String = Nothing 
      For Each person In groupedNames 
       msg += person.Key & "-" & person.Count.ToString & vbCrLf 
      Next 
      MsgBox(msg) 
     End If 
相關問題