Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort DataRow[] using LINQ

Tags:

c#

linq

c#-3.0

DataRow[] drTest contains System.Data.DataRow, say, contains 10 DataRow's. Inside of each DataRow, I have an ItemArray that contains Name and Count. 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.

like image 818
user2423609 Avatar asked Sep 16 '25 12:09

user2423609


1 Answers

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();
like image 97
Timothy Walters Avatar answered Sep 18 '25 09:09

Timothy Walters