Why is List<>.OrderBy LINQ faster than IComparable+List<>.Sort in Debug mode?

前端 未结 4 2201
情歌与酒
情歌与酒 2021-02-19 11:30

I was interested in whether it would be faster to sort my classes using LINQ, or by implementing the IComparable interface and List.Sort. I was quite surprised when the LINQ cod

4条回答
  •  猫巷女王i
    2021-02-19 12:12

    For me, I will use Linq with IComparable(when this is the most or only way to sort). In this case, item is a TestSort: IComparable

    var sorted = ll.OrderBy(item => item); // This automatically used age to compare, as it's defined in CompareTo
    

    ll can be any IEnumerable: List, Array, etc.

    Also in CompareTo you can have multiple way to compare... for instance, you can do something like this:

      public int CompareTo(TestSort other) {
            return this.age != other.age ? this.age.CompareTo(other.age) : this.dateOfBirth.CompareTo(other.dateOfBirth);
        }
    

提交回复
热议问题