在C#中,2D列表(二维列表)通常是通过使用嵌套的List<T>
来实现的,其中外层的List
包含内层的List
,每个内层List
代表一行数据。下面是一些基础概念、优势、类型、应用场景以及常见问题的解答。
List<T>
提供了丰富的API,便于操作和管理数据。List<List<int>>
List<List<string>>
List<List<YourCustomObject>>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个整数型的二维列表
List<List<int>> matrix = new List<List<int>>();
// 添加行
for (int i = 0; i < 3; i++)
{
List<int> row = new List<int>();
for (int j = 0; j < 3; j++)
{
row.Add(i * 3 + j);
}
matrix.Add(row);
}
// 打印二维列表
foreach (var row in matrix)
{
foreach (var item in row)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}
}
解决方法:
List<List<int>> fixedSizeMatrix = new List<List<int>>(new List<int>[3])
{
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6 },
new List<int> { 7, 8, 9 }
};
解决方法:
int element = matrix[1][2]; // 访问第二行第三列的元素
解决方法:
foreach (var row in matrix)
{
foreach (var item in row)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
解决方法:
// 添加新行
matrix.Add(new List<int> { 10, 11, 12 });
// 删除最后一行
matrix.RemoveAt(matrix.Count - 1);
解决方法: 在访问元素之前检查索引是否有效。
if (rowIndex >= 0 && rowIndex < matrix.Count && colIndex >= 0 && colIndex < matrix[rowIndex].Count)
{
int element = matrix[rowIndex][colIndex];
}
else
{
Console.WriteLine("索引越界!");
}
通过以上信息,你应该能够理解和使用C#中的二维列表,并解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云