LINQ to SQL PredicateBuilder [英] LINQ to SQL PredicateBuilder

查看:50
本文介绍了LINQ to SQL PredicateBuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PredicateBuilder,如此处所示 http://www.albahari.com/nutshell/predicatebuilder .aspx ,一切正常,现在我可以将Dynamic LINQ生成为SQL表达式了,但是我不明白的是为什么当我在这样的循环中使用:

Im using the PredicateBuilder as seen here http://www.albahari.com/nutshell/predicatebuilder.aspx, everything works great, and now i can genrate Dynamic LINQ to SQL expressions, but the thing that i dont understand is why when i am on a loop like this:

var inner = PredicateBuilder.False<MyType>();
foreach (var f in Filtermodel.InstrumentsFilterList.Where(s => s.isActive))
        {
          int temp = f.InstrumentID;
          inner = inner.Or(ud => ud.InstrumentId == temp);
        }

为什么必须使用该temp变量?我尝试使用"f"迭代器变量,但它每次迭代仅获得列表中的最后一个值,就像它是通过引用传递的一样.

Why must i use that temp variable?, i try to use the "f" iterator variable but it only get the last value on the list for each iteration, like it is passed by reference...

推荐答案

因为PredicateBuilder正在构建一个表达式,该表达式将在以后的某个时间点执行.当编译器为委托生成闭包时,它会找到在当前作用域中创建的所有值,并将它们也带入闭包中.由于InstrumentID是一种值类型(int),因此初始化和复制该值意味着每个委托/关闭都将携带该值.如果您不是每次都创建该值的副本,则该表达式将仅具有f.InstrumentID的文字引用,而不是其基础值.因此,稍后,当实际执行该表达式时,将对f.InstrumentID进行求值,并将其作为最后设置的值(即上一次迭代)显示出来.

Because PredicateBuilder is building up an expression which will be executed at a later point in time. When the compiler is generating the closure for the delegate, it finds any values which are created in the current scope, and carries them into the closure as well. Since InstrumentID is a value type (int), initializing and copying the value means each delegate/closure will carry that value with it. If you don't create a copy of the value each time, the expression will simply have a literal reference to f.InstrumentID, not to its underlying value. So later on, when the expression is actually executed, f.InstrumentID is evaluated and it will come out as whatever it was last set to, which is the last iteration.

这篇关于LINQ to SQL PredicateBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆