If you find this article useful, consider making a small donation to show your support for this web site and its content.
Free app Developer Interview available here.

Available on the iPhone App Store
Available on the Google Play
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.



Sorting Using C# Lists

by Farooq Kaiser 2. February 2009 04:38
I'll show you how to sort and iterate list object in generic 
 
public class Customer
        {
            public int custId;
            public string custName;
 
            public Customer(int id, string name)
            {
                this.custId = id;
                this. custName = name;
            }
        }
 
List<Customer> cust = new List<Customer>();
 
cust.Add(new Customer(1008, "Microsoft"));
cust.Add(new Customer(999, "Google"));
cust.Add(new Customer(879, "Yahoo"));
cust.Add(new Customer(1206, "Amazon"));

cust.Sort(delegate(Customer c1, Customer c2) 
{ return c1. custName.CompareTo(c2. custName); }); 
 
cust.ForEach(delegate(Customer  c) 
     { Console.WriteLine(String.Format("{0} {1}", c.custId, c.custName)); });
 
  Sorted list
  1206 Amazon
  999  Google
  1008 Microsoft
  879 Yahoo
 
The above code using Lambda Expressions

//with anonymous method
cust.Sort(delegate(Customer c1, Customerc2) 
{ return c1. custName.CompareTo(c2. custName); }); 

//with Lambda Expressions
cust.Sort((c1,c2)=>c1.custName.CompareTo(c2.custName));

//with anonymous method
cust.ForEach(delegate(Customer c) 
{ Console.WriteLine(String.Format("{0} {1}", c.custId, c.custName)); });

//with Lambda Expressions
cust.ForEach(c=> Console.WriteLine(String.Format("{0} {1}", c.custId, c.custName))); 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | C#


comments powered by Disqus
Jobs Autos Real estate Videos Power by Google