Linq OrderBy does not sort a List. How do I sort the list?

前端 未结 5 1715
感动是毒
感动是毒 2020-12-04 02:24

Having issues with the OrderBy clause not having any impact on the sort. I have walked through this in the debugger and insuring this is a case that the sort line of the cod

5条回答
  •  一整个雨季
    2020-12-04 02:29

    OrderBy doesn't sort a List or any other IEnumerable. It produces a new, sorted IEnumerable. So calling ddlOptions.OrderBy(...) doesn't modify ddlOptions.

    If you have a List and wish to sort it, you can use the Sort method - in particular the overload that takes a Comparison as a parameter. This actually sorts the list instead of returning a new IEnumerable.

    Comparison is a delegate representing a function that takes two of T and returns a negative number if the first is "less" than the second, a positive number if the first is "greater" than the second, and zero if one isn't sorted before or after the other.

    In this case you don't have to remember that. Instead, you can just do this:

    ddlOptions.Sort((x, y) => string.CompareOrdinal(x.DisplayText, y.DisplayText));
    

    You're passing in a function that takes two items in the list and returns the comparison result of their DisplayText properties, which will be negative, 0, or positive.

    Sometimes we use OrderBy because it doesn't modify the original list. But if modifying the list is what we want then we can use Sort.

提交回复
热议问题