[英]Linq: X objects in a row
我需要一個linq查詢的幫助,當列表按日期排序時,如果列表包含一行中的x個對象,則返回true。
像這樣:
myList.InARow(x => x.Correct, 3)
如果連續3個屬性為correct == true,則返回true。
不知道該怎么做。
使用GroupAdjacent
擴展,您可以執行以下操作:
var hasThreeConsecutiveCorrect
= myList.GroupAdjacent(item => item.Correct)
.Any(group => group.Key && group.Count() >= 3);
這是使用Rollup
擴展(Select和Aggregate之間的交叉)的另一種方式,它更節省空間:
var hasThreeConsecutiveCorrect
= myList.Rollup(0, (item, sum) => item.Correct ? (sum + 1) : 0)
.Contains(3);
linq中沒有任何內容可以輕松處理這種情況。 但是創建自己的擴展方法相對簡單。
public static class EnumerableExtensions {
public IEnumerable<T> InARow<T>(this IEnumerable<T> list,
Predicate<T> filter, int length) {
int run = 0;
foreach (T element in list) {
if (filter(element)) {
if (++run >= length) return true;
}
else {
run = 0;
}
}
return false;
}
}
更新 :
myList.Aggregate(0,
(result, x) => (result >= 3) ? result : (x.Correct ? result + 1 : 0),
result => result >= 3);
廣義版本 :
myList.Aggregate(0,
(result, x) => (result >= length) ? result : (filter(x) ? result + 1 : 0),
result => result >= length);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.