将2D数组转换为C#中的连接字符串列表 [英] Convert 2D array to list of joined strings in c#

查看:98
本文介绍了将2D数组转换为C#中的连接字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多维对象数组有效地转换为连接数组的列表.

I am wanting to efficiently convert a multidimensional object array into a list of joined arrays.

首先,我将2D数组转换为数组列表:

Firstly, I have converted the 2D array into a list of arrays:

object[,] data; // This contains all the data.
int count = 0;
List<string[]> dataList = data.Cast<string>()
                          .GroupBy(x => count++ / data.GetLength(1))
                          .Select(g => g.ToArray())
                          .ToList();

现在我要做的是创建一个要修剪的列表,然后将每个数组中的所有数据连接起来.为了弄清楚我的意思,我可以使用:

And now what I want to do is create a List where I trim and then join all the data in each array. To clarify what I mean, I can do this using:

List<string> dataListCombined = new List<string>();
foreach (string[] s in dataList)
{
    for (int i = 0; i < s.Length; i++)
    {
        s[i] = s[i].Trim();
    }
    dataListCombined.Add(string.Join(",", s));
}

但是我只想知道是否有一种更有效的方法.我可以使用上面的方法更改LINQ Im吗? 谢谢

but i just want to know if there is a more efficient way of doing it. Can I alter LINQ Im using above to do it? Thanks

推荐答案

在这两个块中,以下LINQ代码将产生与完整代码相同的结果:

Following LINQ code will produce the same results as your complete code in both blocks:

此代码将适用于任何级别(维度)的多维数组

//dimensions in the array
int arrayDimensions = data.Rank;

//create a group of items in each row of the array
//join all items of each group into a comma separated string
//combine all formed strings into a list of strings

List<string> dataListCombined = 
data.Cast<string>().Select((s, i) => new { GroupIndex = i / arrayDimensions, Item = s.Trim()}).
GroupBy(g => g.GroupIndex).Select(g => string.Join(",", g.Select(x => x.Item))).ToList();

这篇关于将2D数组转换为C#中的连接字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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