Define the following variables:
List<int> numbers = new List { 0, 1, 2, 3, 4, 5 };
Func<int, bool> comparator = (int t) => { return t < 3; }
var (listWhereTrue, listWhereFalse) = /* looking for this snippet */;
/// expected output:
/// listWhereTrue = { 0, 1, 2 }
/// listWhereFalse = { 3, 4, 5}
Is there a LINQ combination that I can use to return two IEnumerable, in which one passes the comparator and the other doesn't?
CodePudding user response:
You can use ToLookup
:
List<int> numbers = new List<int> { 0, 1, 2, 3, 4, 5 };
Func<int, bool> comparator = t => t < 3;
var lookup = numbers.ToLookup(i => comparator(i));
var listWhereTrue = lookup[true].ToList();
var listWhereFalse = lookup[false].ToList();
Or MoreLINQ
's Partition
(though it returns IEnumerable<T>
, not a List<T>
):
var (listWhereTrue, listWhereFalse) = numbers.Partition(comparator);