如何拆分 IEnumerable<String>成组 IEnumerable<string>; [英] How can I split an IEnumerable<String> into groups of IEnumerable<string>
问题描述
我有一个 IEnumerable
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
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屋!