Which loop more efficient/preferable – foreach or while loop [closed]

With ten items per list, nobody cares about ten allocations of the enumerator saved by the call of Reset. This is definitely a micro-optimization, even though the second approach does save you some allocations. I would definitely go for more readability of the first approach, or even add some LINQ, like this:

foreach (var list1Value in list1) {
    var tmp = list1Value;
    foreach (var list2Value in list2.Where(item => item == tmp)) {
        // Do something
    }
}

Leave a Comment