tags:

views:

100

answers:

3

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

+2  A: 

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;
Jon Skeet
sorry I actually meant Generic IEnumerable<T>, and the most important thing is how to do it descending
Omu
With the "orderby x.Length" or "orderby x.Length descending" to answer the title but not the question body :)
cyberzed
@Omu: Please be more careful when writing questions. If you're unclear, it wastes both our time and yours.
Jon Skeet
+4  A: 
Enumerable.OrderByDescending

if the problem was that you wanted descending and not ascending

Kikaimaru
+3  A: 

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);
nukefusion