I’ve the following code:
var e = someList.GetEnumerator();
var a = new List<Foo>();
var b = new List<Foo>();
while(e.MoveNext()) {
if(CheckCondition(e.Current)) {
b.Add(e.Current);
break;
}
a.Add(e.Current);
}
while(e.MoveNext())
b.Add(e.Current)
This looks ugly. Basically, iterate through a list and add elements to one list until some condition kicks in, and add the rest to another list.
Is there a better way e.g. using linq ? CheckCondition() is expensive, and the lists can be huge so I’d prefer to not do anything that iterates the lists twice.
Here’s a solution that’s going to enumerate the list twice, but it won’t check the condition the second time, so it should be faster:
IfsomeListimplementsIList<T>, each item will actually be enumerated only once, so there won’t be any penalty.I thought
Skipwas optimized for the case ofIList<T>, but apparently it’s not… However you could easily implement your ownSkipmethod that uses this optimization (see Jon Skeet’s article about this)It would actually be more elegant if there was a
TakeUntilmethod… we can easily create it:With this method, the code becomes: