C# 如何将列表<>转换为多维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/678178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a list<> to a multi-dimensional array?
提问by Melursus
I have the following method signature:
我有以下方法签名:
public void MyFunction(Object[,] obj)
I create this object:
我创建了这个对象:
List<List<Object>> obj = new List<List<Object>>;
Is there an easy way I can convert this to an Object[,]
?
有没有一种简单的方法可以将其转换为Object[,]
?
UPDATE:
更新:
The fact is I like to use List
s because I can easily add a new item. Is there a way I can declare my List<>
object to fit this need? I know the number of columns in my Object[,]
but not the number of rows.
事实是我喜欢使用List
s 因为我可以轻松添加新项目。有没有办法可以声明我的List<>
对象来满足这种需要?我知道我的列数,Object[,]
但不知道行数。
采纳答案by Reed Copsey
No. In fact, these aren't necessarily compatible arrays.
不。事实上,这些不一定是兼容的数组。
[,]
defines a multidimensional array. List<List<T>>
would correspond more to a jagged array ( object[][]
).
[,]
定义一个多维数组。 List<List<T>>
将更多地对应于锯齿状数组 ( object[][]
)。
The problem is that, with your original object, each List<object>
contained in the list of lists can have a different number of objects. You would need to make a multidimensional array of the largest length of the internal list, and pad with null valuesor something along those lines to make it match.
问题在于,对于您的原始对象,List<object>
列表列表中包含的每个对象都可以具有不同数量的对象。您需要创建一个最大长度的内部列表的多维数组,并填充空值或沿着这些行进行填充以使其匹配。
回答by GEOCHET
To be blunt, the answer is no, not easily.
坦率地说,答案是否定的,并不容易。
Perhaps you would like to edit your question to give us more background about why these declarations are needed and we can help you with your root problem?
也许您想编辑您的问题,为我们提供有关为什么需要这些声明的更多背景信息,我们可以帮助您解决根本问题?
Re your update:
重新更新:
I assume you cannot change the function you need to pass this into.
我假设你不能改变你需要传递给它的函数。
I don't see why you cannot just use an object[,]
to begin with. This is my recommendation.
我不明白为什么你不能只使用 anobject[,]
开始。这是我的建议。
I doubt this will help you in your situation, but it might make some of the array working easier on you to start with. Do you know about the .ToArray()
method on a List
?
我怀疑这会在您的情况下帮助您,但它可能会使您开始使用某些阵列更容易。你知道.ToArray()
a上的方法List
吗?
回答by Noldorin
You're not going to get a verysimple solution for this (i.e. a few lines). LINQ/the Enumerable
class isn't going to help you in this case (though it could if you wanted a jagged array, i.e. Object[][]
). Plain nested iteration is probably the best solution in this case.
你不会得到一个非常简单的解决方案(即几行)。Enumerable
在这种情况下,LINQ/类不会帮助你(尽管如果你想要一个锯齿状的数组,它可能会帮助你Object[][]
)。在这种情况下,普通嵌套迭代可能是最好的解决方案。
public static T[,] To2dArray(this List<List<T>> list)
{
if (list.Count == 0 || list[0].Count == 0)
throw new ArgumentException("The list must have non-zero dimensions.");
var result = new T[list.Count, list[0].Count];
for(int i = 0; i < list.Count; i++)
{
for(int j = 0; j < list[i].Count; j++)
{
if (list[i].Count != list[0].Count)
throw new InvalidOperationException("The list cannot contain elements (lists) of different sizes.");
result[i, j] = list[i][j];
}
}
return result;
}
I've included a bit of error handling in the function just because it might cause some confusing errors if you used it on a non-square nested list.
我在函数中包含了一些错误处理,只是因为如果在非方形嵌套列表上使用它可能会导致一些令人困惑的错误。
This method of course assumes that each List<T>
contained as an element of the parent List
is of the same length. (Otherwise you really need to be using a jagged array.)
这种方法当然假设List<T>
作为父元素包含的每个元素List
都具有相同的长度。(否则你真的需要使用锯齿状数组。)
回答by ΩmegaMan
Here is a solution using Linq's Aggregate
extension.
这是使用 LinqAggregate
扩展的解决方案。
Note that the below does not check, nor is concerned if it gets a jagged sub list, it uses the max size of all the sublists and fills in according to the current list. If that is a concern one could add a check to the if
to check for the same count amongst all the sub lists.
请注意,下面不检查,也不关心它是否得到锯齿状的子列表,它使用所有子列表的最大大小并根据当前列表进行填充。如果这是一个问题,可以添加一个检查if
以检查所有子列表中的相同计数。
public static T[,] To2DArray<T>(this List<List<T>> lst)
{
if ((lst == null) || (lst.Any (subList => subList.Any() == false)))
throw new ArgumentException("Input list is not properly formatted with valid data");
int index = 0;
int subindex;
return
lst.Aggregate(new T[lst.Count(), lst.Max (sub => sub.Count())],
(array, subList) =>
{
subindex = 0;
subList.ForEach(itm => array[index, subindex++] = itm);
++index;
return array;
} );
}
Test / Usage
测试/使用
var lst = new List<List<string>>() { new List<string>() { "Alpha", "Beta", "Gamma" },
new List<string>() { "One", "Two", "Three" },
new List<string>() { "A" }
};
var newArray = lst.To2DArray();
Result:
结果: