我怎么可以拆分为IEnumerable&LT;串GT;到了IEnumerable&LT组;串&GT; [英] How can I split an IEnumerable<String> into groups of IEnumerable<string>
问题描述
我有一个的IEnumerable&LT;字符串
>我想分成三组,所以如果我输入了6个项目,我会得到一个 IEnumerable的&LT; IEnumerable的&LT;串&GT;&GT;
与每个两项返回将包含一个的IEnumerable&LT;字符串方式&gt;
这是我的字符串的内容
我在寻找如何做到这一点使用LINQ,而不是一个简单的for循环
感谢
VAR的结果= sequence.Select((S,I)=&gt;新建{值= S,指数= I })
.GroupBy(项目=&GT; item.Index / 3,项目= GT; item.Value);
请注意,这会返回一个的IEnumerable&LT; IGrouping&LT; INT,串&GT;&GT;
这将是功能上类似于你想要什么。但是,如果严格需要将其类型为的IEnumerable&LT; IEnumerable的&LT;串&GT;&GT;
(传递给需要它在C#3.0不支持泛型方差的方法),你应该使用 Enumerable.Cast
:
VAR的结果= sequence.Select((S,I)=&gt;新建{值= S,指数= I})
.GroupBy(项目=&GT; item.Index / 3,项目= GT; item.Value)
.Cast&LT;&IEnumerable的LT;串GT;&GT;();
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.
I am looking for how to do this with Linq rather than a simple for loop
Thanks
var result = sequence.Select((s, i) => new { Value = s, Index = i })
.GroupBy(item => item.Index / 3, item => item.Value);
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&LT;串GT;到了IEnumerable&LT组;串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!