如何使用LINQ拆分为子列表? [英] How to split into sublists using LINQ?

查看:79
本文介绍了如何使用LINQ拆分为子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
使用LINQ将列表拆分为子列表

Possible Duplicate:
Split List into Sublists with LINQ

我正在寻找一种使用LINQ将可枚举分为三个可枚举的方法,以使输入中的每个连续项都位于序列中的下一个子列表中.因此输入

I'm looking for some way to split an enumerable into three enumerables using LINQ, such that each successive item in the input is in the next sublist in in the sequence. So input

{"a", "b", "c", "d", "e", "f", "g", "h"}

会导致

{"a", "d", "g"}, {"b", "e", "h"}, {"c", "f"}

我已经这样做了,但是我确信必须有一种使用LINQ来更优雅地表达这一点的方法.

I've done it this way but I'm sure there must be a way to express this more elegantly using LINQ.

var input = new List<string> {"a", "b", "c", "d", "e", "f", "g", "h"};
var list = new List<string>[3];

for (int i = 0; i < list.Length; i++)
    list[i] = new List<string>();

int column = 0;
foreach (string letter in input)
{
    list[column++].Add(letter);
    if (column > 2) column = 0;
}

推荐答案

这是您要查找的内容: (按列划分)基于先前的帖子进行了修改

This is what you are looking for: (Splits by columns) Modified based on the previous posts

关键区别在于分组方式,使用mod而不是除法.

The key difference is in the group by, using mod instead of division.

我也将其设为通用,以便为您提供正确的类型(与对象类型"代码相对).您可以只对泛型使用类型推断.

Also I made it generic so it gives you back the proper type (as opposed to "object typed" code). You can just use type inference with generics.

public static IEnumerable<IEnumerable<T>> SplitColumn<T>( IEnumerable<T> source ) {
    return source
        .Select( ( x, i ) => new { Index = i, Value = x } )
        .GroupBy( x => x.Index % 3 )
        .Select( x => x.Select( v => v.Value ).ToList() )
        .ToList();
}

这篇关于如何使用LINQ拆分为子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆