How to Sort Data using LINQ

I have been asked allot of questions in the forums lately about LINQ and one question that comes up is how to sort data. A user had an ArrayList of employees and he needed to order them by surname. I said use LINQ! It's as simple as this query:


ArrayList names = new ArrayList(5);
names.Add("Tony Abbot");
names.Add("Tony A Farrow");
names.Add("Tony Charles");
names.Add("Tony Small");
names.Add("Bob Brown");

var query = from p in names.Cast<string>()
let count = p.Split(' ').Length - 1
let surname = p.Split(' ')[count]
let givenname = p.Split(' ')[0]
orderby surname ascending
select new
GivenName = givenname,
Surname = surname

foreach (var item in query)
// item.GivenName
// item.Surname


Dim names As New ArrayList(5)
names.Add("Tony Abbot")
names.Add("Tony A Farrow")
names.Add("Tony Charles")
names.Add("Tony Small")
names.Add("Bob Brown")

Dim query = _
From p In names.Cast(Of String)() _
Let count = p.Split(" "c).Length - 1 _
Let surname = p.Split(" "c)(count) _
Let givenname = p.Split(" "c)(0) _
Order By surname Ascending _
Select New
givenname, Surname = surname
GivenName = givenname, Surname

For Each item In query
' item.GivenName
' item.Surname
Next item

About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at Follow him on twitter @malcolmsheridan

No comments: