如何拆分 IEnumerable<String>成组 IEnumerable<string>; [英] How can I split an IEnumerable&lt;String&gt; into groups of IEnumerable&lt;string&gt;

查看:31
本文介绍了如何拆分 IEnumerable<String>成组 IEnumerable<string>;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 IEnumerable>,我想把它分成三个一组,所以如果我的输入有 6 个项目,我会得到一个 IEnumerable> 返回两个项目,每个项目都包含一个 IEnumerable,其中包含我的字符串内容.

I have an IEnumerable<string> which I would like to split into groups of three so if my input had 6 items i would get a IEnumerable<IEnumerable<string>> returned with two items each of which would contain an IEnumerable<string> which my string contents in it.

我正在寻找如何使用 Linq 而不是简单的 for 循环来做到这一点

I am looking for how to do this with Linq rather than a simple for loop

谢谢

推荐答案

var result = sequence.Select((s, i) => new { Value = s, Index = i })
                     .GroupBy(item => item.Index / 3, item => item.Value);

请注意,这将返回一个 IEnumerable>,它在功能上与您想要的类似.但是,如果您严格需要将其键入为 IEnumerable<IEnumerable(传递给不支持泛型变化的 C# 3.0 中需要它的方法),您应该使用 Enumerable.Cast:

Note that this will return an IEnumerable<IGrouping<int,string>> which will be functionally similar to what you want. However, if you strictly need to type it as IEnumerable<IEnumerable<string>> (to pass to a method that expects it in C# 3.0 which doesn't support generics variance,) you should use Enumerable.Cast:

var result = sequence.Select((s, i) => new { Value = s, Index = i })
                     .GroupBy(item => item.Index / 3, item => item.Value)
                     .Cast<IEnumerable<string>>();

这篇关于如何拆分 IEnumerable<String>成组 IEnumerable<string>;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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