String Sort using LINQ C#
Sorting a string array using LINQ. suppose LINQ array has firstname,lastname ,default sort works on firstname. If user wants to sort on LastName. then you can follow this logic.
name contains format: FirstName,LastName
String[] strFirstLastNames = new String[] {"Amar,josuva","peter,hans","tom,cruise","Preeti,Zinta" };
void SortByFirstName()
{
var query = from name in strFirstLastNames
orderby name
select name;
foreach (String str in query)
{
Console.WriteLine(str);
}
}
{
var query = from name in strFirstLastNames
orderby name
select name;
foreach (String str in query)
{
Console.WriteLine(str);
}
}
OUTPUT(alphabetical order)
--------------------
Amar,josuva
peter,hans
Preeti,Zinta
tom,cruise
peter,hans
Preeti,Zinta
tom,cruise
void SortByLastName()
{
Console.WriteLine();
var query = from name in strFirstLastNames
let lastname = name.Split(new char[]{','})[1]
orderby lastname
select name;
//For Descending orderby lastname descending
foreach (String str in query)
{
Console.WriteLine(str);
}
}
{
Console.WriteLine();
var query = from name in strFirstLastNames
let lastname = name.Split(new char[]{','})[1]
orderby lastname
select name;
//For Descending orderby lastname descending
foreach (String str in query)
{
Console.WriteLine(str);
}
}
OUTPUT(last name, cruise, hans ,josuva,Zinta in sorted order).
----------------------
tom,cruise
peter,hans
Amar,josuva
Preeti,Zinta
peter,hans
Amar,josuva
Preeti,Zinta
Tags: LINQ LET CLAUSE,LINQ ORDERBY clause,LINQ ORDER BY keyword, String Sort using LINQ, String split in LET clause, String sorting in descending order, Order Strings in C#,Arrange Strings in Ascending/descending order.
No comments:
Post a Comment