15

我的代码如下所示:

Collection<NameValueCollection> optionInfoCollection = ....
List<NameValueCollection> optionInfoList = new List<NameValueCollection>();
optionInfoList = optionInfoCollection.ToList();

if(_isAlphabeticalSoting)
   Sort optionInfoList

我尝试了 optionInfoList.Sort() 但它不起作用。

4

4 回答 4

26

使用 sort 方法和 lambda 表达式,真的很容易。

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

上面的示例显示了如何按对象类型的 Name 属性进行排序,假设 Name 是字符串类型。

于 2009-03-03T05:38:59.213 回答
8

如果你只是想Sort()工作,那么你需要实现IComparableIComparable<T>在课堂上。

如果您不介意创建列表,可以使用OrderBy/ ToListLINQ 扩展方法。如果你想用更简单的语法对现有列表进行排序,你可以添加一些扩展方法,启用:

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

例如:

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)));
}
于 2009-03-03T05:43:39.763 回答
2
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);
    }
);
于 2011-09-21T19:26:31.430 回答
1

您需要设置一个比较器,告诉 Sort() 如何排列项目。

查看List.Sort 方法 (IComparer)以获取有关如何执行此操作的示例...

于 2009-03-03T05:26:38.807 回答