[英]How can I sort a datatable using an outside list (prefer linq)?
I have an unsorted datatable with several rows. 我有几行未排序的数据表。 One of my datatable columns is a unique Integer ID. 我的数据表列之一是唯一的Integer ID。
I have a separate method outside of my datatable that is processing information from this table (with some other data) and returning me a sorted list of the IDs in my table. 我在数据表之外有一个单独的方法,该方法正在处理该表中的信息(以及其他一些数据),并向我返回表中ID的排序列表。
What I want to do is represent my datatable in a datagridview, sorted using the list that was returned to me from my method. 我想做的是在datagridview中表示我的数据表,并使用从我的方法返回给我的列表进行排序。 The sorted list is a List(Of Integer) that contains all of the IDs from my table. 排序后的列表是一个List(Of Integer),其中包含表中的所有ID。
result = result
.Where(l => ids.Any(id => id == l.id))
.ToList()
.OrderBy(l => ids.IndexOf(l.id))
You may add a "Sort" column on your datatable: 您可以在数据表上添加“排序”列:
myDataTable.Columns.Add("SortCol", typeof(Int32));
for (int i=0;i<MyDataTable.Rows.Count;i++)
myDataTable.Rows[i]["SortCol"]=mySortedList.IndexOf(myDataTable.Rows[i]["Id"] ;
Then, use a bindingSource to bind the DataTable to the DataGridView: 然后,使用bindingSource将DataTable绑定到DataGridView:
BindingSource myBindingSource = new BindingSource() ;
myGridView.BindingSource = myBindingSource ;
myBindingSource.DataSource = myDataTable ;
Finally, Hide the "SortCol" and Sort the datagridView: 最后,隐藏“ SortCol”并对datagridView进行排序:
myGridView.Columns["SortCol"].Visible = false ;
myBindingSource.Sort = "SortCol ASC" ;
You can use the fact that in a Join
the order of the first collection is preserved: 您可以使用在Join
中保留第一个集合的顺序的事实:
Dim ids = { 4, 2, 3, 1 }
Dim dt = new DataTable()
dt.Columns.Add("ID", GetType( integer))
dt.Rows.Add( { 1 })
dt.Rows.Add( { 2 })
dt.Rows.Add( { 3 })
dt.Rows.Add( { 4 })
Dim query = From id In ids
Join row in dt.AsEnumerable On id Equals row(0)
Select row
query
will now return the data rows as 4, 2, 3, 1
. query
现在将作为返回数据的行4, 2, 3, 1
。
You can use CopyToDataTable
to convert the results back to a Datatable. 您可以使用CopyToDataTable
将结果转换回Datatable。
Here is what I used: (note that keyList is the List(Of Integer) of IDs in my table that have been sorted) 这是我使用的:(请注意,keyList是表中已排序的ID的列表(整数))
Dim sortQuery = From id In keyList
Join row In myTable.AsEnumerable On id Equals row.Field(Of Integer)("ID")
Select row
Dim newtable = sortQuery.CopyToDataTable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.