Question

I think this is a defered execution issue, but maybe i am missing the point somewhat

I have a loop thus

List<int> processed = new List<int>()
foreach(KeyValuePair<int,bool> tbl1 in tables.Where(z=>!processed.Contains(z.Key))){
   //do some stuff...etc 
   processed.Add(someInt);
}

I feel this is very dangerous, but actually does the deferred execution make this work? it does actually seem to be iterating i somewhat gently say 'as expected' but .... question is I guess presumably this is a bad idea, normally messing with a collection that you are iterating over is BAD..

thoughts? thanks

ok to be clear.. the question is

say tables is filled like this

1,true 2,false 3,false 4,false 5,false 6,false

first lap I get the {1,true} in tbl1 and add say 2 to the processed list on the second lap I would get {3,false} in the tbl1 then add 3 and 4 into processed 3rd lap I would get {5,false} in tbl1 is this expected?

if I on lap 4 added 6 to processed would I get {5,false} again on the next go around? again is this expected I guess I just find this somewhat confusing and feel its dangerous, but possibly that is just for me - as its not entirely making sense

n

Was it helpful?

Solution

As you iterate over tables it will always query the current contents of processed... so it will do what you want, but it's not how I'd suggest doing it :)

Aside from anything else, you could use HashSet<int> to avoid an O(n) containment check on each iteration.

However, I suspect you want the functionality of DistinctBy in MoreLINQ:

foreach (var item in tables.DistinctBy(x => x.Key))
{
    // Process the item
}

That won't leave you with a list of processed keys, admittedly... but maybe that's not an issue.

Personally I think it's a shame that LINQ doesn't already have DistinctBy, MaxBy etc, but there we go...

OTHER TIPS

Would grouping your tables help you?

var groups = tables.GroupBy(x=> x.Key);

Depending on what your plans are you could order the groups internally. Or did I get someting wrong?

I think your gut instinct that it's bad is correct :-)

It should work though.

The where function yields results as it compares them so each iteration it will run the lambda and check if the key is in the list.

You should also change that list into a HashSet for performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top