编程构建LINQ查询无局部变量欺骗我 [英] Building a LINQ query programatically without local variables tricking me

查看:107
本文介绍了编程构建LINQ查询无局部变量欺骗我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

魅力(对我)的情况。

假设我的对象是完好的工作状态(即TDD使我觉得他们的工作)。

Assume my objects are in perfect working order (i.e. TDD makes me think they work).

我有这样创建(除缩进正确)的列表:

I have a list that I create like this (except indented properly):

var result = from v in vendors
             from p in v.Products
             orderby p.Name
             select p;

这工作 - 我得到的所有产品全部供应商

This works - I get all products from all vendors.

现在我有一个条件列表,用户在运行时建立起来了。让我们应用它们:

Now I have a list of conditions, built up at runtime by the user. Let's apply them:

foreach (Attribute a in requiredAttributes)
{
    result = result.Where(p => p.Attributes.Contains(a));
}

这可能是原始的,但我认为它会工作。然而,这foreach循环结束后,当您枚举结果,它将包含有requiredAttributes集合的最后一个属性在它的属性属性(也集合)的所有产品。

This may be primitive, but I thought it'd work. However, after this foreach loop is finished, when you enumerate "result" it will contain all products that has the LAST Attribute of the requiredAttributes collection in it's Attributes property (also a collection).

要我来说,这闻起来像一在某处覆盖每个行程槽的循环,只有最后一个适用。

To me, this smells like "a" is overwritten somewhere with each trip trough the loop, and only the last one applies.

短扩展方法的IEnumerable称为ContainsAll(IEnumerable的),或者诸如此类的话,我怎么能达到我想要的,这基本上是一个逻辑与,给我只有拥有所有必需的属性那些产品?

Short of somehow writing an extension method to IEnumerable called ContainsAll(IEnumerable) or something to that effect, how can I achieve what I want, which is basically a logical AND, giving me only those products that has ALL the required attributes?

谢谢!

推荐答案

(编辑的清晰度。)

问题是foreach循环,而在a的变量被捕获,然后将实际上每次改变。下面是该会工作,通过有效地引入了循环的每个迭代一个新变量和捕获该新的变量的修改。

The problem is the foreach loop, and the fact that the "a" variable is being captured and then changed each time. Here's a modification which will work, by effectively introducing a "new" variable for each iteration of the loop, and capturing that new variable.

foreach (Attribute a in requiredAttributes)
{
    Attribute copy = a;
    result = result.Where(p => p.Attributes.Contains(copy));
}



奥马尔的解决方案是一种清洁的,如果你可以使用它,但是这可能会帮助如果你真正的代码实际上是比较复杂的:)

Omer's solution is a cleaner one if you can use it, but this may help if your real code is actually more complicated :)

编辑:还有更多有关问题的这个受封文章 - 向下滚动到比较捕获策略:复杂VS电

There's more about the issue in this closures article - scroll down to "Comparing capture strategies: complexity vs power".

这篇关于编程构建LINQ查询无局部变量欺骗我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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