This article is very useful in term of using lambda expression.I can remember my old days there if you want to do sorting on multiple fields using Arrays or List then you have to write lot of code but now thanks to lambda expression which gives us unique functionality in .Net.
Introduction
Going to introduce Sorting for Arrays,List.
Objective
As we know if we have multiple fields for sorting in array or list then we have lot of difficulties.
Just using Lambda expression we can solve this issue very easily.
Using the code
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sort_Multiple_Fields
{
public class Emplyoee
{
public string fName { get; set; }
public string lName { get; set; }
public DateTime jDate { get; set; }
public Emplyoee(DateTime date, string fname, string lname)
{
this.fName = fname;
this.lName = lname;
this.jDate = date;
}
}
class Program
{
static void Main(string[] args)
{
List<Emplyoee> person = new List<Emplyoee>();
person.Add(new Emplyoee(new DateTime(2007, 1, 1), "Lalit", "Khanna"));
person.Add(new Emplyoee(new DateTime(2008, 2, 2), "Amit", "Singh"));
person.Add(new Emplyoee(new DateTime(2008, 2, 2), "Amit", "Chauhan"));
person.Add(new Emplyoee(new DateTime(2009, 1, 1), "Dot", "Net"));
person = person.OrderBy(sortFname => sortFname.fName).ThenBy(sortLastName => sortLastName.lName).ThenBy(sortJdate => sortJdate.jDate).ToList();
foreach (Emplyoee e in person)
{
Console.WriteLine(e.fName +" "+e.lName);
}
Console.ReadLine();
}
}
}
Conclusion
You will get sorted results.