我有一个2D字符串数组。我想把这个转换成
List<List<string>>如何在C#中实现这一点?
发布于 2016-05-26 18:27:49
使用Linq可以做到这一点。
var result list.Cast<string>()
.Select((x,i)=> new {x, index = i/list.GetLength(1)}) // Use overloaded 'Select' and calculate row index.
.GroupBy(x=>x.index) // Group on Row index
.Select(x=>x.Select(s=>s.x).ToList()) // Create List for each group.
.ToList();检查此example
发布于 2016-05-26 19:15:05
另一种方法是使用LINQ等效于嵌套的for循环:
string[,] array = { { "00", "01", "02"}, { "10", "11", "12" } };
var list = Enumerable.Range(0, array.GetLength(0))
.Select(row => Enumerable.Range(0, array.GetLength(1))
.Select(col => array[row, col]).ToList()).ToList();发布于 2016-05-26 19:15:16
我更喜欢Hari的回答,但是如果由于某些原因你无法访问Linq (.NET框架< 3.5)
List<List<string>> lLString = new List<List<string>>();
string[,] stringArray2D = new string[3, 3] {
{ "a", "b", "c" },
{ "d", "e", "f" },
{ "g", "h", "i" },
};
for (int i = 0; i < stringArray2D.GetLength(0); i++) {
List<string> temp = new List<string>();
for (int j = 0; j < stringArray2D.GetLength(1); j++) {
temp.Add(stringArray2D[i,j]);
}
lLString.Add(temp);
}第一个循环遍历行,下一个循环遍历列。所有列(strings)都添加到单个List<string>对象中,然后在退出内部循环时添加到父List<List<string>>对象中。
我已经包含了这些,以防你所说的2D数组实际上是指jagged array (非矩形)。由于这是一个数组数组,您可以简单地通过索引访问内部数组,然后对其调用.ToList()。
List<List<string>> lLString = new List<List<string>>();
string[][] jaggedStringArray = new string[3][];
jaggedStringArray[0] = new string[] { "a", "b", "c" };
jaggedStringArray[1] = new string[] { "d", "e", "f", "g", "h" };
jaggedStringArray[2] = new string[] { "i" };
for (int i = 0; i < jaggedStringArray.Length; i++) {
lLString.Add(jaggedStringArray[i].ToList());
}如果您使用的是交错数组,并且使用的是LinqFrameworkLinq3.5,则可以将其与>=结合使用,如下所示
List<List<string>> lLString = jaggedStringArray.Select(x => x.ToList()).ToList();https://stackoverflow.com/questions/37458052
复制相似问题