I seem to be having problems executing a lambda expression that I previously assigned to a variable. Here is a small sample C # program that I have compiled:
public class Program
{
public static void Main(string[] args)
{
int[] notOrdered = { 3, 2, 5, 8, 1, 4, 7, 9, 6 };
Print(notOrdered);
IEnumerable<int> ascOrdered = Order(notOrdered, true);
Print(ascOrdered);
IEnumerable<int> descOrdered = Order(notOrdered, false);
Print(descOrdered);
}
static IEnumerable<T> Order<T>(IEnumerable<T> enumerables, bool ascending)
{
Expression<Func<T, object>> selector = (z) => z;
if (ascending)
return enumerables.OrderBy(z => selector);
else
return enumerables.OrderByDescending(z => selector);
}
static void Print<T>(IEnumerable<T> enumerables)
{
foreach(T enumerable in enumerables)
Console.Write(enumerable.ToString() + " ");
Console.WriteLine();
}
}
I want him to generate this output:
3 2 5 8 1 4 7 9 6
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
But vaguely, he makes this conclusion:
3 2 5 8 1 4 7 9 6
3 2 5 8 1 4 7 9 6
3 2 5 8 1 4 7 9 6
Basically, I just want to be able to convey the same expression for two different ordering operations without having to enter it twice, so I assigned it in advance selector. I have a real use case where the lambda expression is really long / messy, and I don't want to duplicate the mess, I would rather just refer to a variable like mine here.
, ) ? ) , ?