c# - 'System.Collections.Generic.List<string>' 到 System.Collections.Generic.List<string>[*,*]

标签 c# arraylist

我在我的项目中使用 C# asp.net。我在其中使用二维数组。名为房间号。当我尝试删除其中的一行时。所以我将数组转换为列表。

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();

我得到了

Error   3   Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<string>[*,*]'

lst = roomno.Cast().ToList();

我的代码中有什么错误?

之后,我打算删除列表中的行,lst.RemoveAt(array_qty);

最佳答案

这个:

List<string>[,] lst = new List<string>[100, 14];

正在声明 List<string> 的二维数组值(value)观。

这个:

roomno.Cast<string>[,]().ToList();

... 由于 [,] 的位置,根本没有意义在类型参数和 () 之间用于方法调用。如果您将其更改为:

roomno.Cast<string[,]>().ToList();

然后它将创建一个 List<string[,]>但它仍然与 List<string>[,] 不同.

此外,roomno只是一个二维字符串数组 - 就 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;
    }
}

关于c# - 'System.Collections.Generic.List<string>' 到 System.Collections.Generic.List<string>[*,*],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9512141/

相关文章:

Java 更改 ArrayList<Double> 中 double 型的格式

c# - 我可以设置动态生成控件的 Desired ClientID

c# - 如何使异步事件连续运行?

c# - 如何引用不同方法的参数?

Java - 按钮从 arrayList 和窗口(jframe)中删除当前项目/对象

java - 创建返回 boolean 值的方法数组并迭代 for-each 循环

c# - 使用 b-tree 索引器访问磁盘

c# - 如何获取最后插入的记录

java - 如何编写一个方法,将单词向后存储在从用户输入接收到的数组列表中,直到输入 "done"?

java - 我怎样才能轻松地将 json 转换为自定义类型的 ArrayList?