C#. How to sort List by field

In this post I'll describe two ways to sort List<T> generic collection by one of it's fields. It's very useful and not easy for beginners.

We have a class "Coupon" with 3 fields. Here it is:

   public class Coupon
        public string action_id {get; set;}
        public string action_name {get; set;}
        public Int32 coupon_number { get; set; }

Let’s create and fill source List<Coupon>:

List<Coupon> unsortedlist = new List<Coupon>();
unsortedlist.Add(new Coupon { action_id = "921", action_name = "test 1", coupon_number = 1});
unsortedlist.Add(new Coupon { action_id = "829", action_name = "test 2", coupon_number = 7});
unsortedlist.Add(new Coupon { action_id = "521", action_name = "test 3", coupon_number = 3});


Now we need to sort this List by field "coupon_number". I usually use one of two ways for sorting List<T>, here they are.


1. Common List<T> sorting by field

We need to add class for compare

    public class CouponComparer : IComparer<Coupon>
        public int Compare(Coupon cl1, Coupon cl2)
            return cl1.coupon_number == cl2.coupon_number ? 0 : (cl1.coupon_number < cl2.coupon_number ? -1 : 1);


And for sorting by field "coupon_number" we need to write this string:

unsortedlist.Sort(new CouponComparer());


We don’t need to create another List<T> and we don’t need to use System.Linq, so our dll will be less size and use less resources, but we use some more code.


2. using System.Linq

Using System.Linq we need to create another List<T> and add using System.Linq. This way is good if it’s not the only using of Linq in your project.

using System.Linq;

List<Coupon> sortedlist = new List<Coupon>();

sortedlist = unsortedlist.OrderBy(x => x.coupon_number).ToList();


No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

MarkiMarta.com. Notes of web-specialist
Since 2009