Click here to Skip to main content
15,923,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Datatable like

Name                ID
Kingshuk Dutta      2
Tapas Nayak         4
Prakash Kiran       7


I've to sort the datatable by Name column but using the LAST NAME only.
It should show like:

Name                ID
Kingshuk Dutta      2
Prakash Kiran       7
Tapas Nayak         4


What I have tried:

The datatable is coming like this, I've to sort it.

I thought of taking the names in a string array and then sort, afterwards insert into datatable. but thats wrong idea. Please suggest.
Posted
Updated 31-Jul-17 21:12pm

If you split the First name and Last name into separate columns it will make working with your data a lot easier.
 
Share this answer
 
Solution 1 provides the simplest way to do this. If, however, you really need to have a single Name field, there is a way to sort it:
C#
dt.AsEnumerable().OrderBy(x => (x.ItemArray[0] as string).Split(' ')[1]).CopyToDataTable(); // where 'dt' is your DataTable

AsEnumerable returns an EnumerableRowCollection<DataRow>, on which you can call OrderBy with a lambda expression that tells to use the second word of the name. This returns an OrderedEnumerableRowCollection<DataRow> and you can call CopyToDataTable to convert this collection into a new DataTable.
 
Share this answer
 
Comments
Karthik_Mahalingam 1-Aug-17 4:00am    
5
Kingshuk_SP 2-Aug-17 2:01am    
one question.

can you explain the use of "Split(' ')[1]" in the query please ???
Kingshuk_SP 2-Aug-17 2:24am    
yeah I got that's for first space we'll get lastname and is sorting. fine.

But if the Name column is like:

Mary Sue Van Pelt
Rose Van Juliet

in such case how can i run a loop ?
Thomas Daniels 2-Aug-17 2:32am    
What do you count as "last name" here? Only the last part? Or everything except the first part?
Kingshuk_SP 2-Aug-17 2:46am    
yeah only last part. 

like in case of the below name:

Mary Sue Van Pelt

"Pelt" would be the last name

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900