简体   繁体   中英

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.

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.

What I want to do is represent my datatable in a datagridview, sorted using the list that was returned to me from my method. The sorted list is a List(Of Integer) that contains all of the IDs from my table.

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 myBindingSource = new BindingSource() ;
myGridView.BindingSource      = myBindingSource ;
myBindingSource.DataSource    = myDataTable ;

Finally, Hide the "SortCol" and Sort the 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:

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 .

You can use CopyToDataTable to convert the results back to a Datatable.

Here is what I used: (note that keyList is the List(Of Integer) of IDs in my table that have been sorted)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM