Sorting a generic list in ascending or descending order

Sorting a generic list can be as easy as 3 lines.  Use the Sort method to accomplish this task.  More info about List<T> can be found here.

 

    class TestSort

    {

        List<Article> MyArticles = new List<Article>();

        public class Article

        {

            private DateTime _createdDate;

            public DateTime CreatedDate

            {

                get { return _createdDate; }

                set { this._createdDate = value; }

            }

        }

 

        public void SortAscending()

        {

            MyArticles.Sort(delegate(Article a, Article b)

            {

                return a.CreatedDate.CompareTo(b.CreatedDate);

            });

        }

 

        public void SortDescending()

        {

            MyArticles.Sort(delegate(Article a, Article b)

            {

                return a.CreatedDate.CompareTo(b.CreatedDate) * -1;

            });

        }

    }

Published Tuesday, February 17, 2009 1:56 AM by Kiyoshi

Comments

# re: Sorting a generic list in ascending or descending order

Sunday, August 30, 2009 11:11 PM by ziaur10

Sabash!!!!

# re: Sorting a generic list in ascending or descending order

Wednesday, April 21, 2010 7:51 AM by lankatechtalk

Thx, This is a good article

# re: Sorting a generic list in ascending or descending order

Wednesday, June 08, 2011 5:10 PM by rhmayer

This worked great until I ran into a case where I'm using a nullable DateTime type.  Any thoughts on that?

Leave a Comment

(required) 
(required) 
(optional)
(required)