Ale*_*yev 7 c# arrays generics data-structures
我想构建二维数组的字符串,其中一维的长度为2.与此类似
string[,] array = new string[,]
{
{"a", "b"},
{"c", "d"},
{"e", "f"},
{"g", "h"}
}
Run Code Online (Sandbox Code Playgroud)
干
List<string[]> list = new List<string[]>();
list.Add(new string[2] {"a", "b"});
list.Add(new string[2] {"c", "d"});
list.Add(new string[2] {"e", "f"});
list.Add(new string[2] {"g", "h"});
list.ToArray();
Run Code Online (Sandbox Code Playgroud)
给我
string[][]
Run Code Online (Sandbox Code Playgroud)
但不是
string[,]
Run Code Online (Sandbox Code Playgroud)
阵列.
只是好奇,是否有动态构建的技巧
string[,]
Run Code Online (Sandbox Code Playgroud)
不知怎的?
小智 18
你可以这样做.
List<KeyValuePair<string, string>>
Run Code Online (Sandbox Code Playgroud)
这个想法是Key Value Pair会模仿你复制的字符串数组.
好吧,您可以相当轻松地编写一个扩展方法来做到这一点。像这样的东西(只进行了非常轻微的测试):
public static T[,] ToRectangularArray<T>(this IEnumerable<T[]> source)
{
if (!source.Any())
{
return new T[0,0];
}
int width = source.First().Length;
if (source.Any(array => array.Length != width))
{
throw new ArgumentException("All elements must have the same length");
}
T[,] ret = new T[source.Count(), width];
int row = 0;
foreach (T[] array in source)
{
for (int col=0; col < width; col++)
{
ret[row, col] = array[col];
}
row++;
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
有点遗憾的是上面的代码使用 T[] 作为元素类型。由于通用不变性,我目前无法制作源代码,IEnumerable<IEnumerable<T>>这会很好。另一种方法可能是引入带有约束的新类型参数:
public static T[,] ToRectangularArray<T,U>(this IEnumerable<U> source)
where U : IEnumerable<T>
Run Code Online (Sandbox Code Playgroud)
有点毛茸茸的,但应该有用。(显然实现也需要一些改变,但基本原理是相同的。)