how to order descending an IEnumerable<T>
with linq or lambda ?
views:
100answers:
3
+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
2010-08-06 08:08:28
sorry I actually meant Generic IEnumerable<T>, and the most important thing is how to do it descending
Omu
2010-08-06 08:11:29
With the "orderby x.Length" or "orderby x.Length descending" to answer the title but not the question body :)
cyberzed
2010-08-06 08:13:22
@Omu: Please be more careful when writing questions. If you're unclear, it wastes both our time and yours.
Jon Skeet
2010-08-06 08:51:32
+4
A:
Enumerable.OrderByDescending
if the problem was that you wanted descending and not ascending
Kikaimaru
2010-08-06 08:11:53
+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
2010-08-06 08:13:24