C# : Sort list on custom property

This question already has an answer here:

  • How to Sort a List<T> by a property in the object 19 answers

  • This might be inefficient, but you could add a DateTime property to your MyEvent class that converts StartDate to a DateTime and sort on that:

    public class MyEvent
    {
        public int EventId{get;set;}
        public MyDate StartDate{get;set;}
        public DateTime MyStartDate { get { return DateTime.Parse(StartDate.MMDDYYYYHHMMSS); } }
    }
    
    var sorted = myEvents.OrderByDescending(e => e.MyStartDate);
    

    Alternatively, you could make the class immutable and do the conversion when instantiating it:

    public class MyEvent
    {
        public MyEvent(int eventId, MyDate startDate)
        {
            EventId = eventId;
            StartDate = startDate;
            MyStartDate = DateTime.Parse(StartDate.MMDDYYYYHHMMSS);
        }
    
        public int EventId{get; private set;}
        public MyDate StartDate{get; private set;}
        public DateTime MyStartDate { get; private set; }
    }
    

    You can write it with Linq OrderyBy() or OrderByDescending method according to your need this way:

    var outputDate = myEvents.OrderByDescending(x=>
                              {
                               DateTime parsedDate;
                               return DateTime.TryParseExact(x.StartDate, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate) ? parsedDate : DateTime.MinValue;
                              });
    

    or proper way would be to create a custom IComparer for it:

    public class StringDateComparer : IComparer<string>
    {
    
        public int Compare(string date1, string date2)
        {
            DateTime parsedDate1;
            DateTime.TryParseExact(date1, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate1);
    
    
            DateTime parsedDate2;
            DateTime.TryParseExact(date2, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate2);
    
    
    
            if (parsedDate1 < parsedDate2)
                return -1;
            if (parsedDate1 > parsedDate2)
                return 1;
    
    
            return 0;
        }
    }
    

    and now call OrderByDescending() overload which takes IComparer object as parameter:

    var outputDate = myEvents.OrderByDescending(x=>x.StartDate,new StringDateComparer());
    
    链接地址: http://www.djcxy.com/p/70938.html

    上一篇: 在c#中对类对象排序

    下一篇: C#:自定义属性的排序列表