Asp.net mvc 2 IEnumerable在foreach循环中未按预期更新(使用;C、MVC2和Linq)

Asp.net mvc 2 IEnumerable在foreach循环中未按预期更新(使用;C、MVC2和Linq),asp.net-mvc-2,linq-to-entities,foreach,ienumerable,Asp.net Mvc 2,Linq To Entities,Foreach,Ienumerable,我有三个表Tbl_列表、Tbl_属性LU和Tbl_列表属性 Tbl_清单保存我的所有清单。 Tbl_AttributesLU拥有许多属性,包括一个带有ID的名称 Tbl_ListingAttribute为每个列表保存许多属性 我想让我的网站的用户搜索列表,同时能够缩小搜索范围的属性附加到每个清单 为此,我首先将用户选择的所有属性作为名为AttributesFromView的列表发送到我的ViewModel 然后,我获取所有列表并将它们放在一个IEnumarable集合中,称为ListingsIn

我有三个表Tbl_列表、Tbl_属性LU和Tbl_列表属性

Tbl_清单保存我的所有清单。 Tbl_AttributesLU拥有许多属性,包括一个带有ID的名称 Tbl_ListingAttribute为每个列表保存许多属性

我想让我的网站的用户搜索列表,同时能够缩小搜索范围的属性附加到每个清单

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

然后,我获取所有列表并将它们放在一个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列表中具有最后一个属性的项目。我有点困惑为什么会发生这种情况,我非常感谢您帮助解决这个问题

同时,我也为标题的模糊表示歉意——我真的不知道如何表达这个问题

提前感谢,


Sheefy

您正在关闭循环变量,该变量为

解决此问题的一种方法是复制循环变量的值:

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);
}

您正在关闭循环变量,即

解决此问题的一种方法是复制循环变量的值:

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);
}

感谢您的解决方案和链接-现在一切正常。非常感谢。感谢您的解决方案和链接-现在一切正常。非常感谢。