Siva
Siva

Reputation: 109

how to sort DataTable column values?

In my c# DataTable data is like this.


Col1


1234 - Siva

3445 - Ram

78454 - Anand

343 - Raj

454 - Balu

I need out put like this


Col1


78454 - Anand

454 - Balu

3445 - Ram

343 - Raj

1234 - Siva

How to sort results based on text after '-' character in the column of DataTable in c#

Upvotes: 0

Views: 988

Answers (1)

sallushan
sallushan

Reputation: 1147

You can try with LINQ

var dt = new System.Data.DataTable();
dt.Columns.Add("UserName");

dt.Rows.Add("1234 - Siva");
dt.Rows.Add("3445 - Ram");
dt.Rows.Add("78454 - Anand");
dt.Rows.Add("343 - Raj");
dt.Rows.Add("454 - Balu");

// dtNew will be new DataTable with sorted lines
var dtNew = dt.AsEnumerable().OrderBy(x => ((string)x["UserName"]).Substring(((string)x["UserName"]).IndexOf("-") + 1).Trim()).CopyToDataTable();

I guess you need 2 namespaces for this

using System.Linq;
using System.Data; 

Upvotes: 1

Related Questions