我在我的项目中使用C#asp.net.我使用2d数组.命名为roomno.当我尝试删除其中的一行时.所以我将数组转换为列表.
static string[,] roomno = new string[100, 14];
List<string>[,] lst = new List<string>[100, 14];
lst = roomno.Cast<string>[,]().ToList();
Error 1 Invalid expression term 'string' in this line...
if i try below code,
lst = roomno.Cast<string>().ToList();
Run Code Online (Sandbox Code Playgroud)
我有
Error 3 Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<string>[*,*]'
Run Code Online (Sandbox Code Playgroud)
lst = roomno.Cast().ToList();
我的代码中的错误是什么?
之后,我计划删除列表中的行, lst.RemoveAt(array_qty);
这个:
List<string>[,] lst = new List<string>[100, 14];
Run Code Online (Sandbox Code Playgroud)
正在声明一个二维数组List<string>.
这个:
roomno.Cast<string>[,]().ToList();
Run Code Online (Sandbox Code Playgroud)
...由于[,]类型参数和()方法调用之间的位置,简单地没有意义.如果您将其更改为:
roomno.Cast<string[,]>().ToList();
Run Code Online (Sandbox Code Playgroud)
然后它会创建一个,List<string[,]>但它仍然不一样List<string>[,].
另外,roomno它只是一个2-D字符串数组 - 就LINQ而言,它实际上是一个字符串序列 - 所以为什么要尝试将它转换为基本上为3维的类型?
目前还不清楚你要做什么或为什么要这样做,但希望这至少有助于解释为什么它不起作用......
说实话,我会尽量避免在同一类型中混合二维数组和列表.有其他自定义类型会有帮助吗?
编辑:LINQ对二维数组的用处不大.它专为单个序列而设计.我怀疑你需要"手动" - 这是一个简短但完整的程序作为例子:
using System;
class Program
{
static void Main(string[] args)
{
string[,] values = {
{"x", "y", "z"},
{"a", "b", "c"},
{"0", "1", "2"}
};
values = RemoveRow(values, 1);
for (int row = 0; row < values.GetLength(0); row++)
{
for (int column = 0; column < values.GetLength(1); column++)
{
Console.Write(values[row, column]);
}
Console.WriteLine();
}
}
private static string[,] RemoveRow(string[,] array, int row)
{
int rowCount = array.GetLength(0);
int columnCount = array.GetLength(1);
string[,] ret = new string[rowCount - 1, columnCount];
Array.Copy(array, 0, ret, 0, row * columnCount);
Array.Copy(array, (row + 1) * columnCount,
ret, row * columnCount, (rowCount - row - 1) * columnCount);
return ret;
}
}
Run Code Online (Sandbox Code Playgroud)