【问题标题】:IEnumerable not updating as expected within foreach loop (using; C#, MVC2 & Linq)IEnumerable 在 foreach 循环中未按预期更新(使用 C#、MVC2 和 Linq)
【发布时间】:2011-01-09 09:06:42
【问题描述】:

我有三个表 Tbl_Listings、Tbl_AttributesLU 和 Tbl_ListingAttributes。

Tbl_Listings 包含我的所有列表。 Tbl_AttributesLU 包含许多属性(一个带有 ID 的名称) Tbl_ListingAttributes 为每个列表保存许多属性。

我希望允许我网站的用户搜索列表,同时能够通过附加到每个列表的属性来缩小搜索范围。

为此,我首先将用户选择的所有属性作为列表发送到我的 ViewModel - 称为 AttributesFromView。

然后,我获取所有列表并将它们放入一个 IEnumarable 集合 - 称为 ListingsInDB。

然后,我创建了一个 foreach 循环,试图根据 AttributesFromView 中的每个属性缩小列表的范围。以下是代码。

IEnumerable<Listing> ListingsInDB = from x in DBEntities.Tbl_ListingSet select x;

foreach (int Attribute in AttributesFromView)
{
    ListingsInDB = (from x in ListingsInDB
                    from a in x.Tbl_ListingAttributes
                    where a.Tbl_AttributesLU.ID == Attribute
                    select x);
}

现在因为我的 ListingsInDB 集合位于 foreach 循环之外,我假设在 foreach 循环的每次迭代中,它应该通过仅选择带有特定属性的列表来缩小集合。因此,在第一次迭代中,它将选择所有具有 AttributesFromView[0] 的列表。然后(在下一次迭代中),从这个新更新的 ListingsInDB 集合中,它将选择所有具有 AttributesFromView[1] 的进一步列表,依此类推......

但这不起作用。相反,它将始终选择 AttributesFromView 列表中具有最后一个属性的项目。我对为什么会发生这种情况有点困惑,非常感谢您在解决问题方面的帮助。

另外,很抱歉标题非常模糊 - 我真的不知道如何表达这个问题。

提前致谢,

笨拙

【问题讨论】:

    标签: asp.net-mvc-2 linq-to-entities foreach ienumerable


    【解决方案1】:

    您正在关闭循环变量 considered harmful

    修复它的一种方法是复制循环变量的值:

    foreach (int attribute in AttributesFromView)
    {
        int attribute2 = attribute;
        ListingsInDB = (from x in ListingsInDB
                        from a in x.Tbl_ListingAttributes
                        where a.Tbl_AttributesLU.ID == attribute2
                        select x);
    }
    

    【讨论】:

    • 感谢您的解决方案和链接 - 现在按预期工作。非常感谢。
    猜你喜欢
    • 2013-12-25
    • 2021-10-06
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多