Does assigning a lambda expression cause it not to execute later?

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; // simple for demo purposes; pretend it complex
        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.

, ) ? ) , ?

+5
3

.

:

object selector = new object();
if (ascending)
    return enumerables.OrderBy(z => selector);
else
    return enumerables.OrderByDescending(z => selector);

:

Func<T, object> selector = (z) => z;
if (ascending)
    return objects.OrderBy(selector);
else
    return objects.OrderByDescending(selector);

, ( - ), :

Expression<Func<T, object>> selector = (z) => z;
var compiledExpression = selector.Compile();
if (ascending)
    return objects.OrderBy(compiledExpression);
else
    return objects.OrderByDescending(compiledExpression);
+9

a) Expression<Func<T,object>> ( ), . , , ( "", ).

b) , :

static IEnumerable<T> Order<T>(IEnumerable<T> enumerables, bool ascending)
{
    if (ascending)
        return enumerables.OrderBy(z => z);
    else
        return enumerables.OrderByDescending(z => z);
}
+7

You do not call selectorjust by comparing an instance of an expression. The right way should be

static IEnumerable<T> Order<T>(IEnumerable<T> enumerables, bool ascending)
{
    Func<T, object> selector = (z) => z;
    if (ascending)
        return enumerables.OrderBy(z => selector(z));
    else
        return enumerables.OrderByDescending(z => selector(z));
}
+1
source

All Articles