c# - 使用 LINQ 聚合子列表

标签 c# linq

我有一个对象列表(即整数),我想使用 LINQ 聚合子列表。

例如:

原始列表: [ 1, 4, 5, 3, 4, 10, 4, 12 ]

子列表: [ [1,4,5,3], [4,5,3,4], [5,3,4,10], [3 ,4,10,4], [4,10,4,12] ]

结果(聚合列表): [ 5, 5, 10, 10, 12 ]

我想为包含其自身和后续 n = 3 元素的每个元素创建最大的子列表。这可以通过 LINQ 实现,还是我需要创建自己的聚合机制?

提前致谢,克里斯蒂安

最佳答案

public IEnumerable<IEnumerable<int>> GetSubLists(int[] collection)
{
   for(int i = 0; i< collection.Length - 3; i++)
       yield return collection.Skip(i).Take(4);
}

GetSubLists(original).Select(l => l.Max());

或者在一行中

int[] original = {1, 4, 5, 3, 4, 10, 4, 12 };
int chunkCount = 4;
Enumerable.Range(0, original.Length - chunkCount + 1).Select(i => original.Skip(i).Take(chunkCount))
 .Select(l => l.Max());

关于c# - 使用 LINQ 聚合子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21829014/

相关文章:

c# - WPF 数据网格 : How to prevent auto change row on enter key pressed?

c# - 如何删除 Log Analytics 数据收集器 API 创建的自定义日志

c# - 我如何检查用户(已创建或未创建)

c# - 将按钮的事件订阅到自定义控件中

C# Linq select object in List where int in object child List<int> 出现 n 次

c# - 使用 LINQ 连接两个表,同时还从第二个表返回空记录

c# - 异步 WebAPI Controller 服务图像 - 挂起的 HTTP 请求

c# - 如何使用linq过滤SelectList

c# - LINQ 按匹配字符位置排序

c# - LINQ-to-XML 到 DataGridView : Cannot edit fields -- How to fix?