Wednesday, May 22, 2019

c# - Calling ToList() within a foreach statement

I recently started a new job and have taken responsibility of an already existing project in order to optimize the code and make it more efficient (e.g. eliminating redundant code, moving long processes off the UI thread, etc.).



I recently came across a method which uses a nested foreach statement in order to compare a list against itself to check for duplicate data. However, it uses the ToList() method directly in the foreach statement. For example:



foreach(ObjectRow Outer_Row in t.ToList()) {
bool bComparing = false;
foreach(ObjectRow Inner_Row in t.ToList()) {
//code for comparing
}
}



I know that this code is generating the list at least twice; once for the outer loop and one for the inner. My question is, is the t.ToList() method actually running for each iteration of the loops? That is, if there are 100 items in t, is ToList() being called a total of 200 times (100 times for the outer loop and 100 times for the inner loop) or is it still only being called twice (once for the outer loop and once for the inner loop)?



I'm thinking that it would be more efficient to do something like the following:



var list = t.ToList();
foreach(ObjectRow Outer_Row in list) {
bool bComparing = false;
foreach(ObjectRow Inner_Row in list) {

//code for comparing
}
}


It should be noted that t is being generated from a LINQ expression, which results in t being an IEnumerable. So would it be even better to simple do this:



foreach(ObjectRow Outer_Row in t) {
bool bComparing = false;
foreach(ObjectRow Inner_Row in t) {

//code for comparing
}
}


Is there any benefit to enumerating over the list vs. the original IEnumerable?



Thanks in advance for any information and/or suggestions.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...