使用LINQ聚合子列表

时间:2014-02-17 12:22:43

标签: 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的可能吗?还是我需要创建自己的聚合机制?

提前致谢,Christian

4 个答案:

答案 0 :(得分:6)

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());

答案 1 :(得分:1)

var result = sublists.Select(sl => sl.Max());
// [5,5,10,10,12]

创建子列表:

List<int> original = new List<int> { 1, 4, 5, 3, 4, 10, 4, 12 };
int sublistSize = 4; 
// check if original size is greater than required sublistSize
var sublists = Enumerable.Range(0, original.Count - sublistSize + 1)
                         .Select(i => original.GetRange(i, sublistSize));

// [[1,4,5,3],[4,5,3,4],[5,3,4,10],[3,4,10,4],[4,10,4,12]]

答案 2 :(得分:0)

    IEnumerable<int[]> GetLists (int[] list, int size )
    {
       return Enumerable.Range(0, list.Length - size + 1).Select(x => list.Skip(x).Take(size).ToArray());
    } 

样品:

    var list = new[] {1, 4, 5, 3, 4, 10, 4, 12};
    var max = GetLists(list, 4).Select(x => x.Max()).ToArray();

答案 3 :(得分:0)

可以使用“滑动窗口”功能构建Sub-lists中间结果。

然后,Result所需的Max()Select()在窗口上映射的函数var originalList = new [] {1, 4, 5, 3, 4, 10, 4, 12}; var sublists = originalList.Window(4); // [ [1,4,5,3], [4,5,3,4], ... ] var result = sublists.Select(Enumerable.Max); // [ 5, 5, 10, 10, 12 ]

Window


高效public static IEnumerable<IEnumerable<T>> Window<T>(this IEnumerable<T> source, int windowSize) { if(windowSize < 1) throw new ArgumentException("windowSize must positive", "windowSize"); var q = new Queue<T>(windowSize); foreach(var e in source) { q.Enqueue(e); if(q.Count < windowSize) continue; // queue not full yet yield return q; q.Dequeue(); } } 功能:

{{1}}