How do I use the IComparable interface?

后端 未结 6 412
后悔当初
后悔当初 2021-02-02 13:40

I need a basic example of how to use the IComparable interface so that I can sort in ascending or descending order and by different fields of the object type I\'m s

6条回答
  •  逝去的感伤
    2021-02-02 14:19

    If you want dynamic sort, you can use LINQ

    var itemsOrderedByNumber = ( from item in GetClasses() orderby item.Number select item ).ToList();
    var itemsOrderedByText = ( from item in GetClasses() orderby item.Text select item ).ToList();
    var itemsOrderedByDate = ( from item in GetClasses() orderby item.Date select item ).ToList();
    

    or "Sort" method of List class:

    List itemsOrderedByNumber2 = new List( GetClasses() );
    itemsOrderedByNumber2.Sort( ( a, b ) => Comparer.Default.Compare( a.Number, b.Number ) );
    
    List itemsOrderedByText2 = new List( GetClasses() );
    itemsOrderedByText2.Sort( ( a, b ) => Comparer.Default.Compare( a.Text, b.Text ) );
    
    List itemsOrderedByDate2 = new List( GetClasses() );
    itemsOrderedByDate2.Sort( ( a, b ) => Comparer.Default.Compare( a.Date, b.Date ) );
    

提交回复
热议问题