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

这个问题在这里已经有了答案:

  • 如何按对象中的属性排序列表<T> 19答案

  • 这可能效率低下,但是您可以将DateTime属性添加到MyEvent类中,该类将StartDate转换为DateTime并对其进行排序:

    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);
    

    或者,您可以使类不可变,并在实例化时进行转换:

    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; }
    }
    

    你可以按照你的需要用Linq OrderyBy()OrderByDescending方法编写它:

    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;
                              });
    

    或者正确的方法是为它创建一个自定义IComparer:

    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;
        }
    }
    

    现在调用以IComparer对象为参数的OrderByDescending()重载:

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

    上一篇: C# : Sort list on custom property

    下一篇: How to sort a list by a specific property in .NET 2.0?