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!!!!

Leave a Comment

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