Method for sorting a list in C#

This question already has an answer here:

  • How to Sort a List<T> by a property in the object 19 answers

  • It's definitely not something you should do manually (unless you're training your algorithmics skills :) ). It will make your code more complex and harder to maintain.

    Just put:

    using System.Linq;
    

    and do this:

    var sorted = list.OrderByDescending(x => x.PersonalNumber).ToList();
    

    you don't need to be Linq ninja to use it. I also strongly recommend to start using it. I think you can agree it's very easy to read and quite obvious what is it doing.

    Ah, and if you're wanting to sort ascending, just use .OrderBy instead of .OrderByDescending.


    If you want to sort list in place, just put Sort :

    list.Sort((x, y) => x.PersonalNumber.CompareTo(y.PersonalNumber));
    

    To sort in descending order, add - :

    list.Sort((x, y) => -x.PersonalNumber.CompareTo(y.PersonalNumber));
    

    For most scenarios, you should use one of the built-in functionalities for sorting, such as List<T>.Sort or Enumerable.OrderBy . I'm assuming that you want to retain your own implementation for the sorting algorithm.

    You can introduce a key selector function as the second argument to your method:

    public static void SelectionSort<TSource, TKey>(
        List<TSource> list, 
        Func<TSource, TKey> keySelector) 
    {
        // With this method the list is sorted in ascending order. 
        //posMin is short for position of min
        int posMin;
        for (int i = 0; i < list.Count - 1; i++) {
            posMin = i;//Set posMin to the current index of array
            for (int j = i + 1; j < list.Count; j++) {
                if (keySelector(list[j]) < keySelector(list[posMin])) {
                    //posMin will keep track of the index that min is in, this is needed when a swap happens
                    posMin = j;
                }
            }
    
            //if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
            TSource temp;
            if (posMin != i) {
                temp = list[i];
                list[i] = list[posMin];
                list[posMin] = temp;
            }
        }
    }
    

    You would then consume this with a lambda expression:

    SelectionSort(persons, (Person p) => p.PersonalNumber);
    
    链接地址: http://www.djcxy.com/p/70950.html

    上一篇: 我怎样才能按名称排序我的流程?

    下一篇: 在C#中对列表进行排序的方法