How can I sort List based on properties of T?

后端 未结 4 876
误落风尘
误落风尘 2020-12-28 18:21

My Code looks like this :

Collection optionInfoCollection = ....
List optionInfoList = new List

        
相关标签:
4条回答
  • 2020-12-28 18:58
    public class Person  {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    List<Person> people = new List<Person>();
    
    people.Sort(
        delegate(Person x, Person y) {
            if (x == null) {
                if (y == null) { return 0; }
                return -1;
            }
            if (y == null) { return 0; }
            return x.FirstName.CompareTo(y.FirstName);
        }
    );
    
    0 讨论(0)
  • 2020-12-28 19:02

    You need to set up a comparer that tells Sort() how to arrange the items.

    Check out List.Sort Method (IComparer) for an example of how to do this...

    0 讨论(0)
  • 2020-12-28 19:10

    Using the sort method and lambda expressions, it is really easy.

    myList.Sort((a, b) => String.Compare(a.Name, b.Name))
    

    The above example shows how to sort by the Name property of your object type, assuming Name is of type string.

    0 讨论(0)
  • 2020-12-28 19:18

    If you just want Sort() to work, then you'll need to implement IComparable or IComparable<T> in the class.

    If you don't mind creating a new list, you can use the OrderBy/ToList LINQ extension methods. If you want to sort the existing list with simpler syntax, you can add a few extension methods, enabling:

    list.Sort(item => item.Name);
    

    For example:

    public static void Sort<TSource, TValue>(
        this List<TSource> source,
        Func<TSource, TValue> selector)
    {
        var comparer = Comparer<TValue>.Default;
        source.Sort((x, y) => comparer.Compare(selector(x), selector(y)));
    }
    public  static void SortDescending<TSource, TValue>(
        this List<TSource> source,
        Func<TSource, TValue> selector)
    {
        var comparer = Comparer<TValue>.Default;
        source.Sort((x, y) => comparer.Compare(selector(y), selector(x)));
    }
    
    0 讨论(0)
提交回复
热议问题