IEnumerable not updating as expected within foreach loop (using; C#, MVC2 & Linq)
I have three tables Tbl_Listings, Tbl_AttributesLU and Tbl_ListingAttributes.
Tbl_Listings holds all of my listings. Tbl_AttributesLU holds a number of attributes (a name with an ID) Tbl_ListingAttributes holds a number of attributes for each listing.
I want to allow users of my site to search for listings while being able to narrow down the search by the attributes attached to each listing.
To do this I first send all the attributes selected by the user to my ViewModel as a list - called AttributesFromView.
Then, I get all my listings and put them in an IEnumarable collection - called ListingsInDB.
I then create a foreach loop trying to narrow down the list based on each attribute in AttributesFromView. The following is the code.
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);
}
Now because my ListingsInDB collection sits outside the foreach loop, I'm assuming that on each iteration of the foreach loop, it should narrow the collection by only selecting the listings with the particular attributes attached. So on the first iteration, it would select all the listings that have AttributesFromView[0]. Then (in the next iteration), from this newly updated ListingsInDB collection it would select all further listings that have AttributesFromView[1] and so on...
This however doe开发者_StackOverflow社区s not work. Instead, it will always select the items with the last attribute in the AttributesFromView List. I'm a little confused as to why this is happening and would really appreciate your help in resolving the issue.
Also, apologies for the title being very vague - I really did not know how to phrase this question.
Thanks in advance,
Sheefy
You are closing over the loop variable, which is considered harmful.
One way to fix it is to make a copy of the value of the loop variable:
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);
}
精彩评论