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:
C#
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
}
VB.NET
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
Tweet
No comments:
Post a Comment