Building a LINQ query programmatically without local variables tricking me

后端 未结 3 1444
-上瘾入骨i
-上瘾入骨i 2020-12-11 15:37

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):



        
相关标签:
3条回答
  • 2020-12-11 16:07

    (Edited for clarity.)

    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 :)

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

    0 讨论(0)
  • 2020-12-11 16:08
    var result = from v in vendors
                 from p in v.Products
                 where requiredAttributes.All(a => p.Attributes.Contains(a))
                 orderby p.Name
                 select p;
    

    HTH.

    0 讨论(0)
  • 2020-12-11 16:20

    I haven't coded it up, but change

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

    to

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

    should fix it too, I think.

    0 讨论(0)
提交回复
热议问题