foreach(var item in items.Where(x => x.SomeCondition == true).Skip(1))
{
item.OneThing = true;
item.AnotherThing = true;
}
For the item
that was skipped using .Skip(1)
, I also need to set .AnotherThing
to true
. I can iterate everything without .Skip(1)
and set .AnotherThing
to true
, then iterate everything with .Skip(1)
and set .OneThing
to true
. Is there a more elegant way to do this, rather than looping through the collection twice?
Edit: What if there was a .YetAnotherThing
property, which needed to be set on the item that was skipped using .Skip(1)
?
Well it sounds like you don't want to use Skip
in this case. Just use a local variable to remember whether this is the first iteration or not.
bool firstItem = true;
foreach(var item in items.Where(x => x.SomeCondition))
{
item.AnotherThing = true;
if (!firstItem)
{
item.OneThing = true;
}
firstItem = false;
}
See more on this question at Stackoverflow