Skip to main content
 首页 » 编程设计

c#之多维数据结构

2024年02月20日8zengkefu

我需要一个包含一行和一列的多维数据结构。

  • 必须能够在数据结构中的任何位置插入元素。示例:{A , B} 我想在 A 和 B 之间插入 C。 {A, C, B}.
  • 动态:不知道数据结构的大小。
  • 另一个示例:我知道要插入元素的位置的 [row][col]。前任。 insert("A", 1, 5),其中A是要插入的元素,1是行,5 是列。

编辑
我希望能够像这样插入。

    static void Main(string[] args) 
    { 
        Program p = new Program(); 
        List<List<string()>> list = new List<List<string>()>(); 
        list.Insert("RAWR", 1, 2); // RAWR is the element to insert, 1 is the row, 2 is the col. 
        list.Insert("Hello", 3, 5); 
        for (int i = 0; i < list.Count; i++) 
        { 
            Console.WriteLine(list[i]); 
        } 
        Console.ReadKey(); 
    } 

当然这不起作用,因为列表不支持此功能。我知道这段代码很糟糕,但我只是想了解我想要完成的事情。

所以从某种意义上说,我会有一个用户来选择要将元素插入到哪个 ROW 和 COL。

请您参考如下方法:

我认为列表的列表应该可以正常工作:

IList<IList<T>> multiDim = new List<IList<T>>(); 

您可以像这样插入新行:

multiDim.Insert(atRow, new List<T>()); 

或在特定行中插入一个新元素:

multiDim[row].Insert(atColumn, myElement); 

请注意,您的列表中需要有足够的元素才能调用Insert;否则,您将得到一个超出范围的异常。解决此问题的最简单方法是编写一个小型实用程序方法,在可以插入之前添加空项:

private static Expand<T>(IList<T> list, int index) { 
    while (list.Count < index) { 
        list.Add(default(T)); 
    } 
} 

重写你的程序如下:

Expand(list, 1); 
list.Insert(1, "HELLO"); 
Expand(list, 5); 
list.Insert(5, "RAWR");