C#语言LIST
时间: 2025-07-04 07:17:53 浏览: 0
在 C# 编程语言中,`List<T>` 是一个泛型集合类,用于存储动态大小的对象序列。它属于 `System.Collections.Generic` 命名空间,并提供了多种方法来操作列表中的元素。
### 创建和初始化 List
可以使用以下方式创建并初始化一个 `List<T>`:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个整数类型的 List
List<int> numbers = new List<int>();
// 添加元素
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
// 遍历 List
Console.WriteLine("List 中的元素:");
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}
```
上述代码演示了如何创建一个整数类型的 `List`,添加元素以及遍历列表[^1]。
### 使用 LINQ 查询 List
`List<T>` 可以与 LINQ(Language Integrated Query)结合使用,以查询和操作数据。例如,筛选出长度大于 3 的字符串:
```csharp
IEnumerable<string> whereList = mList.Where(name =>
{
if (name.Length > 3)
{
return true;
}
else
{
return false;
}
});
foreach (string s in whereList)
{
Console.WriteLine("element in subList: " + s);
}
```
这段代码展示了如何使用 LINQ 方法 `Where` 来过滤 `List` 中的元素[^2]。
### 其他常用操作
- **插入元素**:可以使用 `Insert` 方法在指定位置插入元素。
- **删除元素**:可以使用 `Remove` 或 `RemoveAt` 方法删除特定元素或根据索引删除元素。
- **查找元素**:可以使用 `Find` 方法查找满足条件的第一个元素。
- **排序**:可以使用 `Sort` 方法对列表进行排序。
### 嵌套使用 List
`List<T>` 还支持嵌套使用,即可以创建包含其他 `List<T>` 的列表。例如,创建一个 `List<List<int>>` 来表示二维数组:
```csharp
List<List<int>> matrix = new List<List<int>>();
matrix.Add(new List<int> { 1, 2, 3 });
matrix.Add(new List<int> { 4, 5, 6 });
matrix.Add(new List<int> { 7, 8, 9 });
// 遍历二维列表
foreach (var row in matrix)
{
foreach (int num in row)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
```
此段代码创建了一个二维列表并遍历输出其内容。
通过这些方法,`List<T>` 提供了灵活且强大的功能来管理动态数据集合。
阅读全文
相关推荐

















