How to order asc / dsc with lambda or linq

how to arrange descent IEnumerable<T>using linq or lambda?

+3
source share
3 answers
Enumerable.OrderByDescending

If the problem was that you wanted to go down, not go up

+10
source

If you mean non-generic IEnumerable, you must use Castor OfTypeto get first IEnumerable<T>, then you can use regular OrderBy/ calls OrderByDescending.

For instance:

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 specifying the type in the query expression:

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

EDIT: now that the question is clarified, the form of the query expression is:

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

If you are talking about generic IEnumerable, below is an example 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);
+4
source

Source: https://habr.com/ru/post/1758343/


All Articles