如何使用Lambda或LINQ进行升序/降序排序

3
如何使用linq或lambda对IEnumerable进行降序排序?
3个回答

10
Enumerable.OrderByDescending

如果问题是你想要降序而不是升序


5
如果您需要一个非泛型的IEnumerable,您应该使用Cast或OfType先将其转换为IEnumerable,然后再使用普通的OrderBy / OrderByDescending调用。
例如:
IEnumerable test = new string[] { "abc", "x", "y", "def" };
IEnumerable<string> orderedByLength = test.Cast<string>()
                                          .OrderBy(x => x.Length);

您也可以通过在查询表达式中明确指定类型来实现此操作:

IEnumerable<string> orderedByLength = from string x in test
                                      orderby x.Length
                                      select x;

编辑:现在问题已经澄清,查询表达式格式为:

var query = from value in collection
            orderby value.SomeProperty descending
            select value;

抱歉,我实际上是指通用的IEnumerable<T>,最重要的是如何按降序进行操作。 - Omu
使用"orderby x.Length"或"orderby x.Length descending"来回答标题,而不是问题主体 :) - cyberzed
1
@Omu:在提问时请更加仔细,如果不清楚会浪费我们双方的时间。 - Jon Skeet

4
如果您正在谈论通用的IEnumerable,下面是一个精简的使用示例。
// Using complex type
class Person()
{
    public string Name;
}

IEnumerable<Person> myEnumerable = new List<Person>();
this.myEnumerable.OrderByDescending(person => person.Name)

// Using value type
IEnumerable<int> ints = new List<int>();
ints.OrderByDescending(x => x);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接