Thursday, November 15, 2012

c# Generic List sorting

Here's a quick code snip of sorting a generic list of object, by a DateTime object property in descending order.

1.  Your class has to inherit IComparable
2.  Implement IComparable's CompareTo method
3. After your generic list of objects is built, then call the lists .Sort method.

In this code I needed the LmrMed's serviceDate sorted in descending order.  The Sort method does not create a new list, it changes the order of the nodes in the current list.

I found this article helpful in learning about c# generic list sorting:  http://www.codedigest.com/Articles/CSHARP/84_Sorting_in_Generic_List.aspx


public class LmrMed IComparable<LmrMed>


    {
        public int recId { getset; }
        public string medText { getset; }
        public DateTime? startDate { getset; }
        public DateTime? endDate { getset; }
        public DateTime serviceDate { getset; }

        public LmrMed(int recId, string medText, DateTime startDate, DateTime endDate, DateTime serviceDate)
        {
            this.recId = recId;
            this.medText = medText;
            this.startDate = startDate;
            this.endDate = endDate;
            this.serviceDate = serviceDate;
        }

        public int CompareTo(LmrMed lm)
        {
            return lm.serviceDate.CompareTo(this.serviceDate);
        }



List<LmrMed> lmrMeds = GetMeds(_mrn);
 
            lmrMeds.Sort();

No comments: