Trivial lambdas in LINQ
Edit: Despite the top positions, I don't think this is a good question (see various comments). Sorry for wasted space, but unfortunately I don't have enough reputation to delete my own post.
Is there a better way to create a lambda (or perhaps a predicate or expression that is not a lambda) that returns either 1) A single argument unchanged, or 2) a constant value? Sometimes I come across when using LINQ where the underlying LINQ extension method requires Func<x,y>
, but I only need an input argument or constant.
In a two-year-old question, Jon Skeet argued that there is no shorthand for a function (see LINQ Identity Function? ). Does the same apply to constant expression? Has (or will) change anything (ed) with .NET 4.5 or C # 5?
source to share
If you were looking for some kind of lambda constant, a regular method would be the closest candidate. Let's say it requires <<20> and you want it to return it true
anyway. Instead of writing, collection.SomeLinqMethod(s => true)
you can create a static class with appropriate methods
public static class Expressions
{
public static bool True(string s)
{
return true;
}
}
Then you write
var result = collection.SomeLinqMethod(Expressions.True);
You can also have common methods
public static bool True<T>(T item)
{
return true;
}
source to share