Подсчитать все строки в сетке данных без дубликатов в Vb.net - PullRequest
0 голосов
/ 06 января 2019

Как рассчитать всю строку на DataGridView без дубликатов в VB.NET?

Если строки

AA
BB
CC
DD
BB

Тогда счет должен быть 4.

1 Ответ

0 голосов
/ 06 января 2019

Я создал приложение Sidpe Widnows Forms с DataGridView под названием DataGridview1.

Затем я создал метод подсчета различных строк в DataGridview1, также я добавил вспомогательный метод, чтобы проверить, равны ли два DataGridViewRow с, вот оно (необходимые комментарии в коде):

Public Class Form1
    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Sample data
        DataGridView1.Columns.Add("col1", "col1")
        DataGridView1.Columns.Add("col2", "col2")
        DataGridView1.Columns.Add("col3", "col3")
        DataGridView1.Rows.Add(1, 2, 3)
        DataGridView1.Rows.Add(1, 2, 3)
        DataGridView1.Rows.Add(1, 2, 3)
        DataGridView1.Rows.Add(1, 3, 3)
        DataGridView1.Rows.Add(2, 2, 3)
    End Sub
    Private Function CountDistinctRows() As Integer
        Dim distinctRows As Integer = 0
        Dim alreadyCountedRows = New List(Of DataGridViewRow)
        For Each row As DataGridViewRow In DataGridView1.Rows
            Dim isRowAlreadyCounted As Boolean
            For Each r As DataGridViewRow In alreadyCountedRows
                isRowAlreadyCounted = AreRowsEqual(row, r)
                If isRowAlreadyCounted Then Exit For
            Next
            ' If we have row, which wasn't already counted, we have to add it
            ' to collection of added rows and increment the counter of distinct rows
            If Not isRowAlreadyCounted Then
                alreadyCountedRows.Add(row)
                distinctRows = distinctRows + 1
            End If
        Next
        Return distinctRows
    End Function

    Private Function AreRowsEqual(row1 As DataGridViewRow, row2 As DataGridViewRow)
        ' Sanity check
        If row1.Cells.Count <> row2.Cells.Count Then Throw New ArgumentException("Rows are of different size!")
        For i = 0 To row1.Cells.Count - 1
            If row1.Cells(i).Value <> row2.Cells(i).Value Then Return False
        Next
        Return True
    End Function
End Class
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...