需要通过vb.net获取列中每个不同值的计数

时间:2016-09-20 20:38:52

标签: vb.net linq

我有一个名单列表,我需要计算名称在列中出现的次数。我正在尝试使用LINQ,但我不完全理解下面发生的事情的语法。

  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

1 个答案:

答案 0 :(得分: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