1

After hours of trying and searching, I think its time to share my problem with you right now.

Problem Definition : I have a Dictionary of KeyValuePairs(named filterPool) which includes an integer (PropertyID) and a string(McValue). What I am trying to do is filtering products depending on those KeyValuePairs and return them as a DataTable/List. You may consider this as building dynamic "Where ... And .." clauses as SQL.

Here is the code that I am using :

            foreach (KeyValuePair<int, string> filter in filterPool)
            {
                products = products.Where(i => i.PROPERTYID == filter.Key && i.MCVALUE.Equals(filter.Value));
            }
            return products.ToDataTable();                  

The problem is the foreach loop above seems to work only once, for the latest KeyValuePair available in the Dictionary.

As far as I could find on Stackoverflow, the closest solution to my problem was : this one, also using a Dictionary of values for filtering

There must be a way to achieve the goal of filtering using Dictionary and LINQ; or there's a huge thing that I am missing/ignoring to see somehow.

Hope the problem given is clear enough for all, Thanks ^^

3 Answers 3

2

This is a closure issue. You can solve it by making a temporary:

        foreach (KeyValuePair<int, string> filterTmp in filterPool)
        {
            var filter = filterTmp; // Make a temporary
            products = products.Where(i => i.PROPERTYID == filter.Key && i.MCVALUE.Equals(filter.Value));
        }
        return products.ToDataTable();   

For details on what's happening, see Eric Lippert's post Closing over the loop variable considered harmful.

Also note that this behavior has changed for C# 5. In C# 5/VS2012, this code would work as expected.

1
  • Thanks Reed, I can't try your solution suggestion right now due to a connection problem with remote SQL Server. I'll try it asap! Thanks again for your fast reply.
    – stckvflw
    Aug 9, 2012 at 19:50
1

You're overwriting your products collection on every iteration of your foreach. I'm not sure what the data type on your collection is, but you'll want to do something like this in your foreach instead:

products.AddRange(products.Where(i => i.PROPERTYID == filter.Key && i.MCVALUE.Equals(filter.Value)));

I'm not sure if that makes sense, but it seems like you're trying to create a collection full of products that match your filterPool.

0
0

I think that it's better solved with aggregate:

return filter
    .Aggregate(products, (acc, filter) => acc.Where(i => i.PROPERTYID == filter.Key && i.MCVALUE.Equals(filter.Value)));
    .ToDataTable();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.