Compiled C# Lambda Expressions Performance - c#

Consider the following simple manipulation over a collection:
static List<int> x = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var result = x.Where(i => i % 2 == 0).Where(i => i > 5);
Now let's use Expressions. The following code is roughly equivalent:
static void UsingLambda() {
Func<IEnumerable<int>, IEnumerable<int>> lambda = l => l.Where(i => i % 2 == 0).Where(i => i > 5);
var t0 = DateTime.Now.Ticks;
for (int j = 1; j < MAX; j++)
var sss = lambda(x).ToList();
var tn = DateTime.Now.Ticks;
Console.WriteLine("Using lambda: {0}", tn - t0);
}
But I want to build the expression on-the-fly, so here's a new test:
static void UsingCompiledExpression() {
var f1 = (Expression<Func<IEnumerable<int>, IEnumerable<int>>>)(l => l.Where(i => i % 2 == 0));
var f2 = (Expression<Func<IEnumerable<int>, IEnumerable<int>>>)(l => l.Where(i => i > 5));
var argX = Expression.Parameter(typeof(IEnumerable<int>), "x");
var f3 = Expression.Invoke(f2, Expression.Invoke(f1, argX));
var f = Expression.Lambda<Func<IEnumerable<int>, IEnumerable<int>>>(f3, argX);
var c3 = f.Compile();
var t0 = DateTime.Now.Ticks;
for (int j = 1; j < MAX; j++)
var sss = c3(x).ToList();
var tn = DateTime.Now.Ticks;
Console.WriteLine("Using lambda compiled: {0}", tn - t0);
}
Of course it isn't exactly like the above, so to be fair, I modify the first one slightly:
static void UsingLambdaCombined() {
Func<IEnumerable<int>, IEnumerable<int>> f1 = l => l.Where(i => i % 2 == 0);
Func<IEnumerable<int>, IEnumerable<int>> f2 = l => l.Where(i => i > 5);
Func<IEnumerable<int>, IEnumerable<int>> lambdaCombined = l => f2(f1(l));
var t0 = DateTime.Now.Ticks;
for (int j = 1; j < MAX; j++)
var sss = lambdaCombined(x).ToList();
var tn = DateTime.Now.Ticks;
Console.WriteLine("Using lambda combined: {0}", tn - t0);
}
Now comes the results for MAX = 100000, VS2008, debugging ON:
Using lambda compiled: 23437500
Using lambda: 1250000
Using lambda combined: 1406250
And with debugging OFF:
Using lambda compiled: 21718750
Using lambda: 937500
Using lambda combined: 1093750
Surprise. The compiled expression is roughly 17x slower than the other alternatives. Now here comes the questions:
Am I comparing non-equivalent expressions?
Is there a mechanism to make .NET "optimize" the compiled expression?
How do I express the same chain call l.Where(i => i % 2 == 0).Where(i => i > 5); programatically?
Some more statistics. Visual Studio 2010, debugging ON, optimizations OFF:
Using lambda: 1093974
Using lambda compiled: 15315636
Using lambda combined: 781410
Debugging ON, optimizations ON:
Using lambda: 781305
Using lambda compiled: 15469839
Using lambda combined: 468783
Debugging OFF, optimizations ON:
Using lambda: 625020
Using lambda compiled: 14687970
Using lambda combined: 468765
New Surprise. Switching from VS2008 (C#3) to VS2010 (C#4), makes the UsingLambdaCombined faster than the native lambda.
Ok, I've found a way to improve the lambda compiled performance by more than an order of magnitude. Here's a tip; after running the profiler, 92% of the time is spent on:
System.Reflection.Emit.DynamicMethod.CreateDelegate(class System.Type, object)
Hmmmm... Why is it creating a new delegate in every iteration? I'm not sure, but the solution follows in a separate post.

Could it be that the inner lambdas are not being compiled?!? Here's a proof of concept:
static void UsingCompiledExpressionWithMethodCall() {
var where = typeof(Enumerable).GetMember("Where").First() as System.Reflection.MethodInfo;
where = where.MakeGenericMethod(typeof(int));
var l = Expression.Parameter(typeof(IEnumerable<int>), "l");
var arg0 = Expression.Parameter(typeof(int), "i");
var lambda0 = Expression.Lambda<Func<int, bool>>(
Expression.Equal(Expression.Modulo(arg0, Expression.Constant(2)),
Expression.Constant(0)), arg0).Compile();
var c1 = Expression.Call(where, l, Expression.Constant(lambda0));
var arg1 = Expression.Parameter(typeof(int), "i");
var lambda1 = Expression.Lambda<Func<int, bool>>(Expression.GreaterThan(arg1, Expression.Constant(5)), arg1).Compile();
var c2 = Expression.Call(where, c1, Expression.Constant(lambda1));
var f = Expression.Lambda<Func<IEnumerable<int>, IEnumerable<int>>>(c2, l);
var c3 = f.Compile();
var t0 = DateTime.Now.Ticks;
for (int j = 1; j < MAX; j++)
{
var sss = c3(x).ToList();
}
var tn = DateTime.Now.Ticks;
Console.WriteLine("Using lambda compiled with MethodCall: {0}", tn - t0);
}
And now the timings are:
Using lambda: 625020
Using lambda compiled: 14687970
Using lambda combined: 468765
Using lambda compiled with MethodCall: 468765
Woot! Not only it is fast, it is faster than the native lambda. (Scratch head).
Of course the above code is simply too painful to write. Let's do some simple magic:
static void UsingCompiledConstantExpressions() {
var f1 = (Func<IEnumerable<int>, IEnumerable<int>>)(l => l.Where(i => i % 2 == 0));
var f2 = (Func<IEnumerable<int>, IEnumerable<int>>)(l => l.Where(i => i > 5));
var argX = Expression.Parameter(typeof(IEnumerable<int>), "x");
var f3 = Expression.Invoke(Expression.Constant(f2), Expression.Invoke(Expression.Constant(f1), argX));
var f = Expression.Lambda<Func<IEnumerable<int>, IEnumerable<int>>>(f3, argX);
var c3 = f.Compile();
var t0 = DateTime.Now.Ticks;
for (int j = 1; j < MAX; j++) {
var sss = c3(x).ToList();
}
var tn = DateTime.Now.Ticks;
Console.WriteLine("Using lambda compiled constant: {0}", tn - t0);
}
And some timings, VS2010, Optimizations ON, Debugging OFF:
Using lambda: 781260
Using lambda compiled: 14687970
Using lambda combined: 468756
Using lambda compiled with MethodCall: 468756
Using lambda compiled constant: 468756
Now you could argue that I'm not generating the whole expression dynamically; just the chaining invocations. But in the above example I generate the whole expression. And the timings match. This is just a shortcut to write less code.
From my understanding, what is going on is that the .Compile() method does not propagate the compilations to inner lambdas, and thus the constant invocation of CreateDelegate. But to truly understand this, I would love to have a .NET guru comment a little about the internal stuff going on.
And why, oh why is this now faster than a native lambda!?

Recently I asked an almost identical question:
Performance of compiled-to-delegate Expression
The solution for me was that I shouldn't call Compile on the Expression, but that I should call CompileToMethod on it and compile the Expression to a static method in a dynamic assembly.
Like so:
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("MyAssembly_" + Guid.NewGuid().ToString("N")),
AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
var typeBuilder = moduleBuilder.DefineType("MyType_" + Guid.NewGuid().ToString("N"),
TypeAttributes.Public));
var methodBuilder = typeBuilder.DefineMethod("MyMethod",
MethodAttributes.Public | MethodAttributes.Static);
expression.CompileToMethod(methodBuilder);
var resultingType = typeBuilder.CreateType();
var function = Delegate.CreateDelegate(expression.Type,
resultingType.GetMethod("MyMethod"));
It's not ideal however. I'm not quite certain to which types this applies exactly, but I think that types that are taken as parameters by the delegate, or returned by the delegate have to be public and non-generic. It has to be non-generic because generic types apparently access System.__Canon which is an internal type used by .NET under the hood for generic types and this violates the "has to be a public type rule).
For those types, you can use the apparently slower Compile. I detect them in the following way:
private static bool IsPublicType(Type t)
{
if ((!t.IsPublic && !t.IsNestedPublic) || t.IsGenericType)
{
return false;
}
int lastIndex = t.FullName.LastIndexOf('+');
if (lastIndex > 0)
{
var containgTypeName = t.FullName.Substring(0, lastIndex);
var containingType = Type.GetType(containgTypeName + "," + t.Assembly);
if (containingType != null)
{
return containingType.IsPublic;
}
return false;
}
else
{
return t.IsPublic;
}
}
But like I said, this isn't ideal and I would still like to know why compiling a method to a dynamic assembly is sometimes an order of magnitude faster. And I say sometimes because I've also seen cases where an Expression compiled with Compile is just as fast as a normal method. See my question for that.
Or if someone knows a way to bypass the "no non-public types" constraint with the dynamic assembly, that's welcome as well.

Your expressions are not equivalent and thus you get skewed results. I wrote a test bench to test this. The tests include the regular lambda call, the equivalent compiled expression, a hand made equivalent compiled expression, as well as composed versions. These should be more accurate numbers. Interestingly, I'm not seeing much variation between the plain and composed versions. And the compiled expressions are slower naturally but only by very little. You need a large enough input and iteration count to get some good numbers. It makes a difference.
As for your second question, I don't know how you'd be able to get more performance out of this so I can't help you there. It looks as good as it's going to get.
You'll find my answer to your third question in the HandMadeLambdaExpression() method. Not the easiest expression to build due to the extension methods, but doable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Linq.Expressions;
namespace ExpressionBench
{
class Program
{
static void Main(string[] args)
{
var values = Enumerable.Range(0, 5000);
var lambda = GetLambda();
var lambdaExpression = GetLambdaExpression().Compile();
var handMadeLambdaExpression = GetHandMadeLambdaExpression().Compile();
var composed = GetComposed();
var composedExpression = GetComposedExpression().Compile();
var handMadeComposedExpression = GetHandMadeComposedExpression().Compile();
DoTest("Lambda", values, lambda);
DoTest("Lambda Expression", values, lambdaExpression);
DoTest("Hand Made Lambda Expression", values, handMadeLambdaExpression);
Console.WriteLine();
DoTest("Composed", values, composed);
DoTest("Composed Expression", values, composedExpression);
DoTest("Hand Made Composed Expression", values, handMadeComposedExpression);
}
static void DoTest<TInput, TOutput>(string name, TInput sequence, Func<TInput, TOutput> operation, int count = 1000000)
{
for (int _ = 0; _ < 1000; _++)
operation(sequence);
var sw = Stopwatch.StartNew();
for (int _ = 0; _ < count; _++)
operation(sequence);
sw.Stop();
Console.WriteLine("{0}:", name);
Console.WriteLine(" Elapsed: {0,10} {1,10} (ms)", sw.ElapsedTicks, sw.ElapsedMilliseconds);
Console.WriteLine(" Average: {0,10} {1,10} (ms)", decimal.Divide(sw.ElapsedTicks, count), decimal.Divide(sw.ElapsedMilliseconds, count));
}
static Func<IEnumerable<int>, IList<int>> GetLambda()
{
return v => v.Where(i => i % 2 == 0).Where(i => i > 5).ToList();
}
static Expression<Func<IEnumerable<int>, IList<int>>> GetLambdaExpression()
{
return v => v.Where(i => i % 2 == 0).Where(i => i > 5).ToList();
}
static Expression<Func<IEnumerable<int>, IList<int>>> GetHandMadeLambdaExpression()
{
var enumerableMethods = typeof(Enumerable).GetMethods();
var whereMethod = enumerableMethods
.Where(m => m.Name == "Where")
.Select(m => m.MakeGenericMethod(typeof(int)))
.Where(m => m.GetParameters()[1].ParameterType == typeof(Func<int, bool>))
.Single();
var toListMethod = enumerableMethods
.Where(m => m.Name == "ToList")
.Select(m => m.MakeGenericMethod(typeof(int)))
.Single();
// helpers to create the static method call expressions
Func<Expression, ParameterExpression, Func<ParameterExpression, Expression>, Expression> WhereExpression =
(instance, param, body) => Expression.Call(whereMethod, instance, Expression.Lambda(body(param), param));
Func<Expression, Expression> ToListExpression =
instance => Expression.Call(toListMethod, instance);
//return v => v.Where(i => i % 2 == 0).Where(i => i > 5).ToList();
var exprParam = Expression.Parameter(typeof(IEnumerable<int>), "v");
var expr0 = WhereExpression(exprParam,
Expression.Parameter(typeof(int), "i"),
i => Expression.Equal(Expression.Modulo(i, Expression.Constant(2)), Expression.Constant(0)));
var expr1 = WhereExpression(expr0,
Expression.Parameter(typeof(int), "i"),
i => Expression.GreaterThan(i, Expression.Constant(5)));
var exprBody = ToListExpression(expr1);
return Expression.Lambda<Func<IEnumerable<int>, IList<int>>>(exprBody, exprParam);
}
static Func<IEnumerable<int>, IList<int>> GetComposed()
{
Func<IEnumerable<int>, IEnumerable<int>> composed0 =
v => v.Where(i => i % 2 == 0);
Func<IEnumerable<int>, IEnumerable<int>> composed1 =
v => v.Where(i => i > 5);
Func<IEnumerable<int>, IList<int>> composed2 =
v => v.ToList();
return v => composed2(composed1(composed0(v)));
}
static Expression<Func<IEnumerable<int>, IList<int>>> GetComposedExpression()
{
Expression<Func<IEnumerable<int>, IEnumerable<int>>> composed0 =
v => v.Where(i => i % 2 == 0);
Expression<Func<IEnumerable<int>, IEnumerable<int>>> composed1 =
v => v.Where(i => i > 5);
Expression<Func<IEnumerable<int>, IList<int>>> composed2 =
v => v.ToList();
var exprParam = Expression.Parameter(typeof(IEnumerable<int>), "v");
var exprBody = Expression.Invoke(composed2, Expression.Invoke(composed1, Expression.Invoke(composed0, exprParam)));
return Expression.Lambda<Func<IEnumerable<int>, IList<int>>>(exprBody, exprParam);
}
static Expression<Func<IEnumerable<int>, IList<int>>> GetHandMadeComposedExpression()
{
var enumerableMethods = typeof(Enumerable).GetMethods();
var whereMethod = enumerableMethods
.Where(m => m.Name == "Where")
.Select(m => m.MakeGenericMethod(typeof(int)))
.Where(m => m.GetParameters()[1].ParameterType == typeof(Func<int, bool>))
.Single();
var toListMethod = enumerableMethods
.Where(m => m.Name == "ToList")
.Select(m => m.MakeGenericMethod(typeof(int)))
.Single();
Func<ParameterExpression, Func<ParameterExpression, Expression>, Expression> LambdaExpression =
(param, body) => Expression.Lambda(body(param), param);
Func<Expression, ParameterExpression, Func<ParameterExpression, Expression>, Expression> WhereExpression =
(instance, param, body) => Expression.Call(whereMethod, instance, Expression.Lambda(body(param), param));
Func<Expression, Expression> ToListExpression =
instance => Expression.Call(toListMethod, instance);
var composed0 = LambdaExpression(Expression.Parameter(typeof(IEnumerable<int>), "v"),
v => WhereExpression(
v,
Expression.Parameter(typeof(int), "i"),
i => Expression.Equal(Expression.Modulo(i, Expression.Constant(2)), Expression.Constant(0))));
var composed1 = LambdaExpression(Expression.Parameter(typeof(IEnumerable<int>), "v"),
v => WhereExpression(
v,
Expression.Parameter(typeof(int), "i"),
i => Expression.GreaterThan(i, Expression.Constant(5))));
var composed2 = LambdaExpression(Expression.Parameter(typeof(IEnumerable<int>), "v"),
v => ToListExpression(v));
var exprParam = Expression.Parameter(typeof(IEnumerable<int>), "v");
var exprBody = Expression.Invoke(composed2, Expression.Invoke(composed1, Expression.Invoke(composed0, exprParam)));
return Expression.Lambda<Func<IEnumerable<int>, IList<int>>>(exprBody, exprParam);
}
}
}
And the results on my machine:
Lambda:
Elapsed: 340971948 123230 (ms)
Average: 340.971948 0.12323 (ms)
Lambda Expression:
Elapsed: 357077202 129051 (ms)
Average: 357.077202 0.129051 (ms)
Hand Made Lambda Expression:
Elapsed: 345029281 124696 (ms)
Average: 345.029281 0.124696 (ms)
Composed:
Elapsed: 340409238 123027 (ms)
Average: 340.409238 0.123027 (ms)
Composed Expression:
Elapsed: 350800599 126782 (ms)
Average: 350.800599 0.126782 (ms)
Hand Made Composed Expression:
Elapsed: 352811359 127509 (ms)
Average: 352.811359 0.127509 (ms)

Compiled lambda performance over delegates may be slower because Compiled code at runtime may not be optimized however the code you wrote manually and that compiled via C# compiler is optimized.
Second, multiple lambda expressions means multiple anonymous methods, and calling each of them takes little extra time over evaluating a straight method. For example, calling
Console.WriteLine(x);
and
Action x => Console.WriteLine(x);
x(); // this means two different calls..
are different, and with second one little more overhead is required as from compiler's perspective, its actually two different calls. First calling x itself and then within that calling x's statement.
So your combined Lambda will certainly have little slow performance over single lambda expression.
And this is independent of what is executing inside, because you are still evaluating correct logic, but you are adding additional steps for compiler to perform.
Even after expression tree is compiled, it will not have optimization, and it will still preserve its little complex structure, evaluating and calling it may have extra validation, null check etc which might be slowing down performance of compiled lambda expressions.

Related

C# IQueryable use dictionary inside Where throws Unable to create a constant value of type Exception

I am using the dictionary inside the IQueryable lambda linq throws the
Unable to create a constant value of type 'System.Collections.Generic.KeyValuePair`2
Code :
Dictionary<int, int> keyValues = new Dictionary<int, int>();
IQueryable<Account> = context.Account
.Where(W => keyValues
.Where(W1 => W1.Key == S.AccountID)
.Where(W1 => W1.Value == S.Balance)
.Count() > 0);
Details:
I have the data inside the dictionary like this
AccountID Balance
1 1000
2 2000
3 3000
I want the user which have the (ID = 1 AND Balance = 1000) OR (ID = 2 AND BALANCE = 2000) OR (ID = 3 AND BALANCE = 3000)
So how can I write the lambda for it ?
Edited
Thanks #caesay, Your answer help me lots.
I want one more favor from you.
From you answer I create the expression which look like below:
private static Expression<Func<Accounting, bool>> GenerateExpression(Dictionary<int, int> lstAccountsBalance)
{
try
{
var objAccounting = Expression.Parameter(typeof(Accounting));
Expression expr = null;
const bool NOT_ALLOWED = false;
if (lstAccountsBalance != null && lstAccountsBalance.Count > 0)
{
var clauses = new List<Expression>();
foreach (var kvp in lstAccountsBalance)
{
clauses.Add(Expression.AndAlso(
Expression.Equal(Expression.Constant(kvp.Key), Expression.Property(objAccounting, nameof(Accounting.ID))),
Expression.Equal(Expression.Constant(kvp.Value), Expression.Property(objAccounting, nameof(Accounting.Balance)))
));
}
expr = clauses.First();
foreach (var e in clauses.Skip(1))
{
expr = Expression.OrElse(e, expr);
}
var notAllowedExpr = Expression.AndAlso(
Expression.Equal(Expression.Constant(NOT_ALLOWED), Expression.Property(objAccounting, nameof(Accounting.ALLOWED))),
Expression.Equal(Expression.Constant(true), Expression.Constant(true))
);
expr = Expression.And(notAllowedExpr, expr);
}
var allowedExpr = Expression.AndAlso(
Expression.Equal(Expression.Constant(!NOT_ALLOWED), Expression.Property(objAccounting, nameof(Accounting.ALLOWED))),
Expression.Equal(Expression.Property(objAccounting, nameof(Accounting.ID)), Expression.Property(objAccounting, nameof(Accounting.ID)))
);
if (expr != null)
{
expr = Expression.OrElse(allowedExpr, expr);
}
else
{
expr = allowedExpr;
}
return Expression.Lambda<Func<Accounting, bool>>(expr, objAccounting);
}
catch (Exception ex)
{
throw objEx;
}
}
After that I compiled the expression like this:
Expression<Func<Accounting, bool>> ExpressionFunctions = GenerateExpression(lstAccountsBalance);
var compiledExpression = ExpressionFunctions.Compile();
And I used like this:
.Select(S => new
{
Accounting = S.Accounts
.Join(context.AccountInfo,
objAccounts => objAccounts.ID,
objAccountInfo => objAccountInfo.ID,
(objAccounts, objAccountInfo) => new Accounting
{
ID = objAccounts.ID,
Balance = objAccountInfo.Balance,
})
.Where(W => W.ID == user.ID)
.AsQueryable()
.Where(W => compiledExpression(W))
.Select(S1 => new Accounting()
{
ID = S1.ID,
Balance = S1.Balance
})
.ToList(),
}
And it throws the exception with the message:
System.NotSupportedException: The LINQ expression node type 'Invoke'
is not supported in LINQ to Entities.
Without Compile
Without the compile it works like charm. It gives the output want I want.
Expression<Func<Accounting, bool>> ExpressionFunctions = GenerateExpression(lstAccountsBalance);
Use:
.Select(S => new
{
Accounting = S.Accounts
.Join(context.AccountInfo,
objAccounts => objAccounts.ID,
objAccountInfo => objAccountInfo.ID,
(objAccounts, objAccountInfo) => new Accounting
{
ID = objAccounts.ID,
Balance = objAccountInfo.Balance,
})
.Where(W => W.ID == user.ID)
.AsQueryable()
.Where(ExpressionFunctions)
.Select(S1 => new Accounting()
{
ID = S1.ID,
Balance = S1.Balance
})
Thank you..
Everything inside of a EF linq query needs to be compiled to an Expression tree, and then to SQL, but the dictionary is an IEnumerable so there is no way that EF could know how to compile that.
You can either build the expression tree yourself, or use the System.Linq.Dynamic nuget package to build the sql yourself.
The example using System.Linq.Dynamic, first install the nuget package and add the using to the top of your file, then there will be a Where overload that takes a string as a parameter:
context.Account.Where(
String.Join(" OR ", keyValues.Select(kvp => $"(ID = {kvp.Key} AND Balance = {kvp.Value})")));
Essentially, everything inside of the Where clause will be executed directly as SQL, so be careful to use the Where(string, params object[]) overload to paramaterize your query if accepting user input.
The expression tree (untested) approach might look like the following:
var account = Expression.Parameter(typeof(Account));
var clauses = new List<Expression>();
foreach(var kvp in keyValues)
{
clauses.Add(Expression.AndAlso(
Expression.Equal(Expression.Constant(kvp.Key), Expression.Property(account, nameof(Account.AccountID))),
Expression.Equal(Expression.Constant(kvp.Value), Expression.Property(account, nameof(Account.Balance)))
));
}
var expr = clauses.First();
foreach (var e in clauses.Skip(1))
expr = Expression.OrElse(e, expr);
context.Account.Where(Expression.Lambda<Func<Account, bool>>(expr, account));
Essentially inside the foreach loop we're creating all of the (ID = ... AND Balance = ...) and then at the end we join them all with an OR.

using int.TryParse with Queryable and expression

I am new to Expressions in c#.
Expression code
var parameter = Expression.Parameter(typeof(int), "param");
var constant = Expression.Constant(5, typeof(int));
var equal = Expression.Equal(parameter, constant);
var lambdaExpression = Expression.Lambda<Func<int, bool>>(equal, parameter);
var compiledExpression = lambdaExpression.Compile();
Query contains a string value and I want to apply expresion only if the value is convertible to int
int test;
query = query.Where(i => int.TryParse(i.Key, out test) && compiledExpression(test));
This returns an error saying int.TryParse is not supported.
Any way to solve this?
You can't use out parameters there.
1) var v = q.Where(x => x.All(c => c >= '0' && c <= '9'));
2) use regex instead of All
3) write a simple method that calls Int32.Parse and just returns a bool to hide the out param
for #3:
static bool SafeIntParse(string s)
{
int n;
return Int32.TryParse(s, out n);
}
var v = q.Where(x => SafeIntParse(x));
The SafeIntParse() method is, of course, a separate static method.
EDIT:
for the regex method:
Regex regex = new Regex("^\\d+$", RegexOptions.Compiled);
var v = q.Where(x => regex.Match(x).Success);
Of course, make the regex object a static object of the class.

Compose filters without the presence of a collection?

I think I might be having a temporary mental glitch here, so excuse me if this is a dumb question but I am wondering if one can compose filters so they can be applied to a collection:
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4 };
Func<int, bool> filter = GetFilter();
IEnumerable<int> result = a.Where(filter);
}
private static Func<int, bool> GetFilter()
{
Func<int, bool> filter = c => c % 2 == 0;
// What if I wanted to further refine my filter here?
// For instance, add a ceiling of 10
return filter;
}
I believe you'd have to add a reference to the original filter to avoid a recursive call.
var previousFilter = filter;
filter = c => previousFilter(c) && c <= 10;
return f => c <= 10 && filter(c);

EF 6: The result of a query cannot be enumerated more than once

Is there any way to avoid "The result of a query cannot be enumerated more than once" exception without using ToList()?
Here is a simplified version of my code:
var entities = _db.Trades.Where(t => t.A > 10);
int totalCount = entities.Count();
entities = entities.Where(t => t.B > 10);
int totalCountAfterAdditionalFilter = entities.Count();
I cannot call ToList() due to performance considerations. I know that I could just generate one more IQueryable, but that seems wrong (I have more filters like this). Could I somehow preserve/duplicate the IQueryable after my first call of Count()?
Thanks!
No, you can't achieve your desired result like that. As an alternative you can, however, save your filters to variables and then compose them as needed:
Func<Trade, bool> filter1 = t => t.A > 10;
Func<Trade, bool> filter2 = t => t => t.B > 10;
Func<Trade, bool> compositeFilter = t => filter1(t) && filter2(t);
int totalCount = _db.Trades.Count(filter1);
int totalCountAfterAdditionalFilter = _db.Trades.Count(compositeFilter);
//Need more?
compositeFilter = t => compositeFilter(t) && t.C > 100;
int totalAfterMoreFilters = _db.Trades.Count(compositeFilter);
may be:
Trades.Where(x => x.A > 10).Select(x => new { i = 1, j = x.B > 10 ? 1 : 0}).
GroupBy(y => y.i).
Select(g => new { c = g.Count(), = g.Sum(z => z.j)})
That's give you the 2 informations in one query.

Rewriting a Linq query to use if / else and ditch the var

I've recently started playing with Linq (cue groans), and am trying to get the following to compile. Now, the whereclause part uses DynamicLinq, which works fine; it's the var placeholder variable that the compiler wants a real class for; unfortunately, I am using what I believe is an anonymous class, and am not sure how to take it from here. Any suggestions?
var query;
if(whereclause != string.Empty)
{
query = Directory.GetFiles(LRSettings.Default.OperatingDirectory, LRSettings.Default.FileExtension,
SearchOption.AllDirectories).AsQueryable()
.Select(Filename => new { Filename, new FileInfo(Filename)
.LastWriteTime, new FileInfo(Filename).Extension, new FileInfo(Filename).Length })
.Where(whereclause);
}
else
{
query = Directory.GetFiles(LRSettings.Default.OperatingDirectory,
LRSettings.Default.FileExtension,
SearchOption.AllDirectories)
.AsQueryable()
.Select(Filename => new { Filename, new FileInfo(Filename).LastWriteTime, new FileInfo(Filename).Extension, new FileInfo(Filename).Length });
}
Since it seems like the only difference in your query is whether or not to include a WHERE clause, you should just be able to do this:
var query = Directory.GetFiles(LRSettings.Default.OperatingDirectory, LRSettings.Default.FileExtension, SearchOption.AllDirectories)
.AsQueryable()
.Select(Filename => new { Filename, new FileInfo(Filename).LastWriteTime, new FileInfo(Filename).Extension, new FileInfo(Filename).Length });
if(whereclause != string.Empty)
{
query = query.Where(whereclause);
}
Since you're using an IEnumerable, I don't think you have to worry about pulling too much data without the Where() clause, since it doesn't get enumerated until you access query in some fashion (like binding to a form or whatnot).
Two immediate options are to use ?: or to extract the common/starting query.
For the former:
bool expr = SomeTrueOrFalseValue();
var l = new [] { 1,2,3 };
// both "true" and "false" branches unify an IEnumerable<int>
var q = expr
? l
: l.Where(x => x > 1);
// q typed as IEnumerable<int>
For the latter:
var q = l.AsEnumerable();
// q is typed as IEnumerable<int>
if (!expr) {
q = q.Where(x => x > 1);
}
// q is still typed as IEnumerable<int> - can't be changed after var
An assignment must be included in a var declaration so the variable's type can be determined.
But without var:
IEnumerable<int> q; // not practical/possible for complex types
if (expr) {
q = l;
} else {
q = l.Where(x => x > 1);
}

Categories