c# - Linq:连续 X 个对象

标签 c# arrays linq

我需要有关 linq 查询的帮助,当列表按日期排序时,如果列表连续包含 x 个对象,该查询将返回 true。

像这样:

myList.InARow(x => x.Correct, 3)

如果连续 3 个属性正确 == 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);

关于c# - Linq:连续 X 个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16283021/

相关文章:

c# - 如何在 linq 中对子列表求和?

c# - Linq lambda 表达式至少得到一个重复项和非重复项

c# - 来自 ViewModel 和 DispatchTimer 的 RelayCommand

java - 如何读取 JSON 数组,Android Java

java - 如何找到对数组进行排序所需的最大组数?

c++ - 如何判断数组元素的类型?

javascript - 为什么我的 asp 文件上传控件文本框是可点击的?

c# - 开发Visual C++和C#有什么意义?

c# - 如何动态添加降序到orderby?

c# - 不能将 null 值分配给类型为 System.Int32 的成员,该类型是不可为 null 的值类型