Joshua Honig
Joshua Honig

Reputation: 13215

Trivial lambdas in LINQ

Edit: Despite the upvotes I don't think this is a good question anymore (see various comments). Sorry for the wasted space, but unfortunately I lack the rep to delete my own post.

Is there a better way of creating a lambda (or perhaps a predicate or expression that is not a lambda) that returns either 1) The sole argument unchanged or 2) a constant value? I encounter this occasionally when using LINQ where a basic LINQ extension method requires a Func<x,y> but I only need the input argument or a constant.

In a two year-old question Jon Skeet asserted that there is no reduction for the identity function (see LINQ identity function?). Is same true of a constant expression? Has (or will) anything chang(ed) with .NET 4.5 or C#5?

Upvotes: 3

Views: 217

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112447

If you were looking for a kind of lambda constant, a regular method would be the closest candidate. Let us say a Func<string,bool> is required and you want it to return it true in any case. Instead of writing collection.SomeLinqMethod(s => true) you could create a static class with appropriate methods

public static class Expressions
{
    public static bool True(string s)
    {
        return true;
    }
}

Then you would write

var result = collection.SomeLinqMethod(Expressions.True);

You could also have generic methods

public static bool True<T>(T item)
{
    return true;
}

Upvotes: 2

Aducci
Aducci

Reputation: 26674

you don't need to specify a predicate for the Count method

.Count()

Upvotes: 7

Related Questions