C# 实现list
时间: 2025-03-14 12:06:13 AIGC 浏览: 51
### C# 中 List 的使用方法及示例代码
在 C# 中,`List<T>` 是一种泛型集合类,位于 `System.Collections.Generic` 命名空间下。它允许动态调整大小,并提供了丰富的操作方法来管理其中的元素。
#### 添加多个元素到列表
可以通过 `AddRange` 方法一次性向列表中添加多个元素。以下是具体说明和示例代码:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
numbers.AddRange(new int[] { 1, 2, 3, 4 }); // 向列表中添加多个整数
Console.WriteLine(string.Join(", ", numbers)); // 输出:1, 2, 3, 4
}
}
```
上述代码展示了如何利用 `AddRange` 方法将一个数组中的所有元素添加到列表中[^1]。
---
#### 将列表转换为字典
如果需要将 `List<T>` 转换为 `Dictionary<TKey, TValue>`,可以借助 LINQ 提供的功能完成此操作。以下是一个具体的例子:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 }
};
Dictionary<string, int> dictionary = people.ToDictionary(person => person.Name, person => person.Age);
foreach (var entry in dictionary)
{
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}
// 输出:
// Key: Alice, Value: 30
// Key: Bob, Value: 25
}
}
```
这段代码演示了如何通过 LINQ 的 `ToDictionary` 方法将 `List<T>` 转换为字典[^2]。
---
#### 比较两个列表的内容
为了验证两个列表是否完全相同(即它们具有相同的顺序和内容),可以采用多种方式实现。下面展示了一种基于 LINQ 查询的方式:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> listA = new List<int> { 1, 2, 3 };
List<int> listB = new List<int> { 1, 2, 3 };
bool areEqual = listA.SequenceEqual(listB); // 判断两列表是否相等
Console.WriteLine(areEqual ? "Lists are equal." : "Lists differ."); // 如果相等则打印“Lists are equal.”
}
}
```
这里采用了 `SequenceEqual` 方法来对比两个列表的内容及其排列次序[^3]。
---
#### 遍历列表中的每一项
当需要逐一访问列表中的每个元素时,推荐使用 `foreach` 循环语句。下面是两种常见的写法之一:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "John", "Jane", "Doe" };
foreach (string name in names) // 或者使用 var 关键字代替显式的类型声明
{
Console.WriteLine(name);
}
// 输出:
// John
// Jane
// Doe
}
}
```
该片段体现了如何运用 `foreach` 结构迭代整个列表内的项目[^4]。
---
#### 总结
以上分别阐述了有关于 C# 中 `List<T>` 类型的一些基本功能与实际应用案例,包括但不限于批量插入数据、映射至其他容器形式以及判定相似度等方面的知识点。
阅读全文
相关推荐
















