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;

            });

        }

    }

14 Comments

Comments have been disabled for this content.