The n => n ... what does that do?
It just maps any value to itself. It's an identity function.
Why not just say OrderBy(n)?
Because n isn't a variable in scope - it wouldn't be valid to call it like that. That's not a lambda expression, so it would just try to use n as a normal method argument.
Your code is just trying to say "order this sequence by the whole of each element" rather than projecting each element to some other value, but there's no way of saying that directly.
OrderBy requires a projection from the element type to the ordering key type - it's just that in this case we want the identity projection.
You could write your own extra extension method:
public static IEnumerable<T> OrderNaturally<T>(this IEnumerable<T> source)
{
return source.OrderBy(item => item);
}
And then change your original statement to:
IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderNaturally();
if you found that more readable.
Alternatively, you could create a Functions class with some useful static readonly fields:
public static class Functions<T>
{
public static readonly Func<T, T> Identity = x => x;
public static readonly Func<T, T> DefaultValue => x => default(T);
public static readonly Func<T, string> ToString = x => x == null ? null : x.ToString();
...
}
Then:
IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0)
.OrderBy(Functions<int>.Identity)
I don't think I would do that... I'm just suggesting things to think about :)
int F(int x) { return x; }, then you could use.OrderBy(F)IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);. Saying OrderBy(Pet) wouldn't be helpful since OrderBy doesn't know how to arrange a Pet.