定義以下變數:
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}
是否有一個 LINQ 組合可用于回傳兩個 IEnumerable,其中一個通過比較器,另一個不通過?
uj5u.com熱心網友回復:
您可以使用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(雖然它回傳IEnumerable<T>,而不是 a List<T>):
var (listWhereTrue, listWhereFalse) = numbers.Partition(comparator);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/498012.html
