C#如何使用相同的方法对不同的元素进行排序

时间:2016-03-17 17:12:04

标签: c# list sorting

我应该使用哪些参数来使用相同的方法对不同的元素进行排序?现在我有4个不同元素的方法副本。

public static void SortByMÄRKE()
    {
        for (int i = 0; i < newklädDataList.Count; i++)
        {
            int minst = i;

            for (int j = i + 1; j < newklädDataList.Count; j++)
            {
                if (newklädDataList[minst].märke.CompareTo(newklädDataList[j].märke) > 0)
                {
                    minst = j;
                }
            }
            if (i < minst)
            {
                Swap(minst, i);
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

您需要使您的方法对集合中项目的类型以及要排序的属性类型具有通用性。然后你需要传递你的收藏和选择器。您要排序的项目类型必须实现自己的IComparable才能使用CompareTo。就像这样。

public static void YourSort<T,U>(this IList<T> collection, Func<T, U> selector) 
    where U : IComparable<U>
{
    for (int i = 0; i < collection.Count; i++)
    {
        int minst = i;

        for (int j = i + 1; j < collection.Count; j++)
        {
            if (selector(collection[minst]).CompareTo(selector(collection[j])) > 0)
            {
                minst = j;
            }
        }
        if (i < minst)
        {
            var temp = collection[minst];
            collection[minst] = collection[i];
            collection[i] = temp;
        }
    }
}

并称之为

newklädDataList.YourSourt(x => x.märke);

答案 1 :(得分:0)

public static List<T> sort(List<T> inputList) 

将是您的方法标题,然后您将编写可以完全与类型无关的代码。每当您需要该类型的新对象或该类型的集合时,您可以像这样使用T:

T newobj = new T();
List<T> newList = new List<T>();