.

sorting lists using delegates / lambda expressions

 

using System;
using System.Collections.Generic;

public class Person
{
       public Person(string name, int age)
       {
              this.name = name;
              this.age = age;
       }
       public string name ;
       public int age;
}      
 
public class MyClass
{
 
       public static void Main()
       {
              List<Person> Plist = new List<Person>();
              Plist.Add(new Person("Mike", 35));
              Plist.Add(new Person("Andy",50));
              Plist.Add(new Person("Louis",60));
              Plist.Add(new Person("John",22));
            
              Console.WriteLine("********* unsorted *******************");

              foreach(Person p in Plist)
                     Console.WriteLine(p.name + " ," + p.age.ToString());

              Console.WriteLine("********* sorted by age *************");

              //lambda expression
              Plist.Sort((Person a,Person b) => a.age.CompareTo(b.age) );

              Plist.ForEach(delegate(Person p) {
              Console.WriteLine(p.name + " ," + p.age.ToString());});

              Console.WriteLine("********* sorted by name ************");            

              //delegate
              Plist.Sort(delegate(Person a,Person b) { return  a.name.CompareTo(b.name); });

              Plist.ForEach((Person p) => Console.WriteLine(p.name + " ," + p.age.ToString()));

              Console.WriteLine("*************************************");
              Console.WriteLine("... press any key");
              Console.ReadKey();
       }
}

 


Output:

********* unsorted *******************
Mike ,35
Andy ,50
Louis ,60
John ,22
********* sorted by age *************
John ,22
Mike ,35
Andy ,50
Louis ,60
********* sorted by name ************
Andy ,50
John ,22
Louis ,60
Mike ,35
*************************************
… press any key

What's your thoughts on this?

*

Protected by WP Anti Spam