C#数组,List,Dictionary的相互转换
时间: 2024-04-29 16:21:44 浏览: 107
C#数组中List, Dictionary的相互转换问题
在C#中,数组、List和Dictionary是常见的数据结构。下面介绍它们之间的相互转换方法。
1. 数组转List
```csharp
int[] arr = { 1, 2, 3 };
List<int> list = arr.ToList();
```
2. List转数组
```csharp
List<int> list = new List<int>() { 1, 2, 3 };
int[] arr = list.ToArray();
```
3. 数组转Dictionary
```csharp
string[] arr = { "a", "b", "c" };
Dictionary<int, string> dict = arr.Select((s, i) => new { Key = i, Value = s }).ToDictionary(p => p.Key, p => p.Value);
```
4. List转Dictionary
```csharp
List<string> list = new List<string>() { "a", "b", "c" };
Dictionary<int, string> dict = list.Select((s, i) => new { Key = i, Value = s }).ToDictionary(p => p.Key, p => p.Value);
```
5. Dictionary转数组
```csharp
Dictionary<int, string> dict = new Dictionary<int, string>() { { 0, "a" }, { 1, "b" }, { 2, "c" } };
string[] arr = dict.Values.ToArray();
```
6. Dictionary转List
```csharp
Dictionary<int, string> dict = new Dictionary<int, string>() { { 0, "a" }, { 1, "b" }, { 2, "c" } };
List<string> list = dict.Values.ToList();
```
阅读全文