how to order asc/dsc with lambda or linq

32,078

Solution 1

Enumerable.OrderByDescending

if the problem was that you wanted descending and not ascending

Solution 2

If you mean a non-generic IEnumerable, you should use Cast or OfType to get an IEnumerable<T> first, then you can use the normal OrderBy / OrderByDescending calls.

For example:

IEnumerable test = new string[] { "abc", "x", "y", "def" };
IEnumerable<string> orderedByLength = test.Cast<string>()
                                          .OrderBy(x => x.Length);

You can also do this by explicitly stating the type in a query expression:

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

EDIT: Now that the question has been clarified, the query expression form is:

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

Solution 3

If your talking about a generic IEnumerable, below is a trimmed down example of usage.

// 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);
Share:
32,078
Omu
Author by

Omu

https://youtu.be/h-K2sMmUlxA http://youtu.be/0fFLZuQ20Qw https://github.com/omuleanu/ValueInjecter http://demo.aspnetawesome.com http://prodinner.aspnetawesome.com

Updated on August 06, 2020

Comments

  • Omu
    Omu over 3 years

    how to order descending an IEnumerable<T> with linq or lambda ?