Alex Rivera | Logout

split a list using linq

Asked 2011-01-06T01:01:40.680
9

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.

c#
Edit
Report

1 Answer

1

This will end up going over the items in the first list more than once, but only calls through CheckCondition the first time:

var a = someList.TakeWhile(e => !CheckCondition(e));
var b = someList.Skip(a.Count());
answered 2011-01-06T01:13:59.733

Your Answer