我怎么可以拆分为IEnumerable<串GT;到了IEnumerable&LT组;串> [英] How can I split an IEnumerable<String> into groups of IEnumerable<string>

查看:150
本文介绍了我怎么可以拆分为IEnumerable<串GT;到了IEnumerable&LT组;串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的IEnumerable<字符串>我想分成三组,所以如果我输入了6个项目,我会得到一个 IEnumerable的< IEnumerable的<串>> 与每个两项返回将包含一个的IEnumerable<字符串方式> 这是我的字符串的内容

我在寻找如何做到这一点使用LINQ,而不是一个简单的for循环

感谢


解决方案

  VAR的结果= sequence.Select((S,I)=>新建{值= S,指数= I })
                     .GroupBy(项目=> item.Index / 3,项目= GT; item.Value);

请注意,这会返回一个的IEnumerable< IGrouping< INT,串>> 这将是功能上类似于你想要什么。但是,如果严格需要将其类型为的IEnumerable< IEnumerable的<串>> (传递给需要它在C#3.0不支持泛型方差的方法),你应该使用 Enumerable.Cast

  VAR的结果= sequence.Select((S,I)=>新建{值= S,指数= I})
                     .GroupBy(项目=> item.Index / 3,项目= GT; item.Value)
                     .Cast<&IEnumerable的LT;串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屋!

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