Sort DataRow[] using LINQ
17,987
Solution 1
A great way of playing with LINQ is using LINQPad. Here's a quick sample I wrote and tested to answer your question:
var table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Count", typeof(int));
table.Rows.Add("A", 5);
table.Rows.Add("B", 7);
table.Rows.Add("C", 1);
table.Rows.Add("D", 8);
table.Rows.Add("E", 9);
table.Rows.Add("F", 6);
table.Rows.Add("G", 3);
table.Rows.Add("H", 2);
table.Rows.Add("I", 4);
var sorted = table.Rows.Cast<DataRow>()
.OrderByDescending(row => row[1]);
// If you are using LINQPad you can test this using the following line:
sorted.Dump();
Solution 2
This should give you what you are looking for:
var result = drTest.OrderByDescending(dr => dr[1]);
Solution 3
You can use the following LINQ query to sort your item array in descending order.
var result = drTest.OrderByDescending(itemArray => itemArray [1]);
or
var result = from row in drtest
orderby row[1] descending
select row;
For more information, you can go through LINQ - Ordering Operators.
Author by
user2423609
Updated on June 27, 2022Comments
-
user2423609 almost 2 years
DataRow[] drTest contains
System.Data.DataRow
, say, contains 10DataRow
's. Inside of each DataRow, I have an ItemArray that containsName
andCount
. Now I want to sort the DataRow[] drTest in descending order based on the ItemArray second record count.Example:
DataRow[] drTest contains At [0] Index - ItemArray[0] - "A" - ItemArray[1] - 5 At [1] Index - ItemArray[0] - "B" - ItemArray[1] - 7
I want to order drTest in descending order, so that drTest[1] should come up.