If I have a collection:
List<T> collection;
and I need to perform two test on this collection, which is more efficient:
foreach(T t in collection.where(w => w.value == true))
{
t.something = true;
}
foreach(T t in collection.where(w => w.value2 == true))
{
t.something2 = true;
}
Or
foreach(T t in collection)
{
if (t.value == true)
{
//check 1
}
if (t.value2 == true)
{
//check 2
}
}
I think it’ll be the later because I presume that each where will iterate the collection but just wanted to be sure I wasn’t missing something?
I think it might change according the collection size. However I would go with the second code.
The first code iterates the entire collection twice (one per
where) and then iterates each result once.The second code iterates just once the entire collection. Also, it’s cleaner.