Let's say I have someList of things I want to split into two separate lists by some condition.
I've thought of 3 options:
// 1 - two Where's
var trueGroup = someList.Where(x => x.SomeCondition);
var falseGroup = someList.Where(x => !x.SomeCondition);
// 2 - groupby the condition, then ToDictionary
var groupedByCondition = someList.GroupBy(x => x.SomeCondition)
.ToDictionary(x => x.Key, x => x.ToList());
var trueGroup = groupedByCondition[true];
var falseGroup = groupedByCondition[false];
// 3 - groupby the condition, then First
var groupedByCondition = someList.GroupBy(x => x.SomeCondition);
var trueGroup = groupedByCondition.First(x => x.Key).ToList();
var falseGroup = groupedByCondition.First(x => !x.Key).ToList();
All 3 definitely work, but I'm looking for the most efficient way to do this. I'm fairly certain option #1 is least efficient since it needs to iterate the full list twice (please correct me if I'm wrong about that), and options #2 + #3 are probably equally efficient (at best one of them might be a micro-optimization).
However, something keeps nagging me that I'm forgetting a very obvious solution. Is there a more efficient/generally accepted way to do this that I'm simply not thinking of?
var (evens, odds) = Enumerable.Range(0, 10).Partition(x => x % 2 == 0);. Unlike the question's attempts, you get back actual lazily-evaluatedIEnumerable<>s that can be used immediately. There's an overload that can be used to return custom results too, so if you really want lists,.Partition(...,(left,right)=>(left.ToList(),right.ToList())foreach, or even better, aforloop. 2) Do you rather want to optimize memory usage, becausesomeListis huge? 3) IssomeListalready materialized? 4) Is a materialized result acceptable or not? 5) What exactly does the following code do with the result?