来自 Vb.Net 数据表的不同行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34855016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Distinct Rows From Vb.Net DataTable
提问by DareDevil
I have a scenario, in which I have to apply distinct filter onto DataTableand find the rows only which are distinct,
I am using dt.DefaultView.ToTable(True, Columns)this statement but no effect.
我有一个场景,我必须在其中应用不同的过滤器DataTable并仅找到不同的行,我正在使用dt.DefaultView.ToTable(True, Columns)此语句但没有效果。
Here is my chunk of code..
这是我的代码块..
Try
Dim dTable As New DataTable()
dTable.Columns.Add("AutoID")
dTable.Columns.Add("AnotherID")
dTable.Columns.Add("CitY")
Dim row As DataRow = Nothing
For i As Integer = 0 To 4
row = dTable.NewRow()
row("AutoID") = i + 1
row("AnotherID") = i + 10
row("City") = "Vetican"
dTable.Rows.Add(row)
Next
dTable.Rows.Add(6, "11", "Oslo")
dTable.Rows.Add(7, "12", "Toronto")
Dim TobeDistinct As String() = {"AnotherID"}
Dim dtDistinct As DataTable = GetDistinctRecords(dTable, TobeDistinct)
Catch ex As Exception
End Try
and the method ..
和方法..
Public Shared Function GetDistinctRecords(ByVal dt As DataTable, ByVal Columns As String()) As DataTable
Dim dtURecords As New DataTable()
dtURecords = dt.DefaultView.ToTable(True, Columns)
Return dtURecords
End Function
回答by Tim Schmelter
Which rows do you want to keep and which rows should be removed? If you just want to keep one row per AnotherIDit seems to be arbitrary to keep Veticaninstead of Oslo. Maybe you want to concat both as in Vetican, Oslo.
您要保留哪些行以及应删除哪些行?如果您只想保留一行,AnotherID那么保留Vetican而不是Oslo. 也许你想像在Vetican, Oslo.
I would use Linqinstead:
我会用Linq:
Dim resultTable = dTable.Clone() ' empty table same columns
Dim idGroups = dTable.AsEnumerable().GroupBy(Function(r) r.Field(Of String)("AnotherID"))
For Each grp In idGroups
Dim r As DataRow = resultTable.Rows.Add()
r.SetField("AutoID", grp.First().Field(Of String)("AutoID"))
r.SetField("AnotherID", grp.Key)
Dim cities = From row In grp Select row.Field(Of String)("City")
r.SetField("City", String.Join(", ", cities))
Next


