6

假设我有一个数组。

string[] temp = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };

我想用逗号加入他们,每 3 个项目如下所示。

string[] temp2 = { "a,b,c", "d,e,f", "g,h,i", "j" };

我知道我可以使用

string temp3 = string.Join(",", temp);

但这给了我结果

"a,b,c,d,e,f,g,h,i,j"

有人有想法吗?

4

4 回答 4

12

一种快速简便的方法,将您的项目分成三个部分:

string[] temp = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };

string[] temp2 = temp.Select((item, index) => new 
{
    Char = item,
    Index = index
})
.GroupBy(i => i.Index / 3, i => i.Char)
.Select(grp => string.Join(",", grp))
.ToArray();

更新为使用.GroupBy允许您指定元素选择器的重载,因为我认为这是一种更简洁的方法。结合@Jamiec的回答。

这里发生了什么:

  1. 我们将 的每个元素投影到一个新元素中——一个具有和属性temp的匿名对象。CharIndex
  2. 然后,我们通过项目索引和 3 之间的整数除法的结果对生成的 Enumerable 进行分组。使用第二个参数 to .GroupBy,我们指定我们希望组中的每个项目都是Char匿名对象的属性。
  3. 然后,我们.Select再次调用来投影分组的元素。这次我们的投影函数需要调用string.Join,将每组字符串传递给该方法。
  4. 在这一点上,我们有一个IEnumerable<string>看起来像我们想要的样子,所以只需调用ToArray从我们的 Enumerable 创建一个数组。
于 2013-08-15T13:09:14.020 回答
5

您可以将Chunk方法(归功于 CaseyB)与string.Join

string[] temp2 = temp.Chunk(3).Select(x => string.Join(",", x)).ToArray();

/// <summary>
/// Break a list of items into chunks of a specific size
/// </summary>
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunksize)
{
    while (source.Any())
    {
        yield return source.Take(chunksize);
        source = source.Skip(chunksize);
    }
}
于 2013-08-15T13:08:28.240 回答
4

可以通过将 Linq 语句链接在一起来完成:

var grouped = temp.Select( (e,i) => new{ Index=i/3, Item=e})
              .GroupBy(x => x.Index, x=> x.Item)
              .Select( x => String.Join(",",x) );

现场示例:http ://rextester.com/AHZM76517

于 2013-08-15T13:12:13.443 回答
3

您可以使用MoreLINQ批处理:

var temp3 = temp.Batch(3).Select(b => String.Join(",", b));
于 2013-08-15T13:05:04.257 回答