寻找2D数组到C#中的字符串,寻找最优雅的方式 [英] Convert 2D array to string in C#, looking for most elegant way

查看:52
本文介绍了寻找2D数组到C#中的字符串,寻找最优雅的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不敢相信没有聪明的方法可以从2D阵列中获得类似的东西,
在这种情况下int[,] a:

I cannot believe there is no smart way to get something like this from a 2D array,
in this case int[,] a:

"{1,2,3},{4,5,6},{7,8,9}"

我已经阅读了许多类似的问题,并了解到string.Join()仅可用于锯齿状阵列(在2D模式下).但是我不希望使用它们,因为初始化更加复杂,而且当我所有长度相同的行分布在内存中的多个位置时,感觉很不好.

I have read many similar questions and learned that string.Join() can only be used on jagged arrays (in 2D). But I don't want to use them because of the more complex initialization and because it just feels bad when my rows, which all have the same length, are spread over several places in memory.

这是我的正常"代码:

var s = "";
for (int i = 0; i < a.GetLength(0); i++) {
    if (i > 0) s += ',';
    s += '{';
    for (int j = 0; j < a.GetLength(1); j++) {
        if (j > 0) s += ',';
        s += a[i, j];
    }
    s += '}';
}

这里是一个打高尔夫球"的人:

And here a "golfed" one:

var s = "{";
var i = 0;
foreach (var item in a) s += (i++ > 0 ? i % a.GetLength(1) == 1 ? "},{" : "," : "") + item;
s += '}';

:)-也不是很优雅,可读性也很差.

:) - not really elegant, too, and the readability is more than bad.

有什么建议吗?我对Linq持开放态度,因为它不一定要快.我有兴趣提高代码的美观度,而不是仅仅将其移至扩展方法.

Any suggestions? I'm open to Linq, since it doesn't have to be fast. I'm interested in improving elegance of the code, but not by just moving it to an extension method.

推荐答案

Linq解决方案,而不是性能明智的解决方案.

Linq solution, not performance wise.

var str = string.Join(",", a.OfType<int>()
    .Select((value, index) => new {value, index})
    .GroupBy(x => x.index / a.GetLength(1))
    .Select(x => $"{{{string.Join(",", x.Select(y => y.value))}}}"));

请注意,您不能在2d数组上使用Select,但是可以使用OfType,它将返回2d数组的可枚举值,枚举器将水平遍历2d数组.

Note that you cant Select on 2d array, but you can use OfType which will return an enumerable for 2d array, the enumerator will traverse through 2d array horizontally.

x.index / a.GetLength(1)只是将每个索引除以总行数.因此,如果您有3行,则索引将等效地分布在3行中.

x.index / a.GetLength(1) simply divides each index to total number of rows. so if you have 3 rows, your indexes will be distributed through 3 rows equivalently.

最后一个字符串连接在每个组上进行.

lastly string join is operated on each group.

更简化的版本. (分组结果选择器内的格式)

A little more simplified version. (format inside result selector of grouping)

var str = string.Join(",", a.OfType<int>()
    .Select((value, index) => new {value, index})
    .GroupBy(x => x.index / a.GetLength(1), x => x.value,
        (i, ints) => $"{{{string.Join(",", ints)}}}"));

这篇关于寻找2D数组到C#中的字符串,寻找最优雅的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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