[英]How can I convert a list<> to a multi-dimensional array?
我有以下方法簽名:
public void MyFunction(Object[,] obj)
我創建了這個 object:
List<List<Object>> obj = new List<List<Object>>;
有沒有一種簡單的方法可以將其轉換為Object[,]
?
事實上,我喜歡使用List
,因為我可以輕松添加新項目。 有沒有辦法我可以聲明我的List<>
object 來滿足這個需求? 我知道我的Object[,]
中的列數,但不知道行數。
不。事實上,這些不一定兼容 arrays。
[,]
定義了一個多維數組。 List<List<T>>
將更多地對應於鋸齒狀數組( object[][]
)。
問題在於,對於您的原始 object,列表列表中包含的每個List<object>
可以具有不同數量的對象。 您需要創建一個內部列表最大長度的多維數組,並用 null 值或類似的東西填充以使其匹配。
你不會得到一個非常簡單的解決方案(即幾行)。 LINQ/ Enumerable
class 在這種情況下不會為您提供幫助(盡管如果您想要一個鋸齒狀數組,即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;
}
我在 function 中包含了一些錯誤處理,因為如果在非方形嵌套列表中使用它可能會導致一些令人困惑的錯誤。
當然,這種方法假定作為父List
的元素包含的每個List<T>
具有相同的長度。 (否則你真的需要使用鋸齒狀數組。)
這是使用 Linq 的Aggregate
擴展的解決方案。
請注意,下面不檢查,也不關心是否得到一個鋸齒狀的子列表,它使用所有子列表的最大大小並根據當前列表填充。 如果這是一個問題,可以在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;
} );
}
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();
結果:
坦率地說,答案是否定的,不容易。
也許您想編輯您的問題,為我們提供更多關於為什么需要這些聲明的背景信息,我們可以幫助您解決根本問題?
我假設您無法更改需要將其傳遞到的 function。
我不明白為什么你不能只使用object[,]
開始。 這是我的建議。
我懷疑這會對您的情況有所幫助,但它可能會使某些陣列在您開始時更容易工作。 你知道List
上的.ToArray()
方法嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.