Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>()如何赋值
时间: 2023-12-16 20:06:17 浏览: 30
这个 Dictionary 的方法是通过添加键/值对来赋值。例如,如果要将 "key1" 映射到一个包含 1、2、3 的整数列表,可以这样写:
dict.Add("key1", new List<int> { 1, 2, 3 });
或者,如果你想要先创建一个列表并向其中添加一些元素,可以这样写:
List<int> list = new List<int> { 1, 2, 3 };
dict.Add("key1", list);
希望这能帮到你!
相关问题
c# 建立N个分组 比如N个Dic <string,List<>>字典
可以使用一个循环来创建指定数量的字典,例如:
```
int N = 5; // 指定要创建的字典数量
List<Dictionary<string, List<object>>> dictionaries = new List<Dictionary<string, List<object>>>();
for (int i = 0; i < N; i++)
{
Dictionary<string, List<object>> dict = new Dictionary<string, List<object>>();
dictionaries.Add(dict);
}
```
这样就可以创建一个包含指定数量的字典的列表,每个字典都是一个 `Dictionary<string, List<object>>` 类型的对象。你可以根据需要修改 `N` 的值和字典的键值类型、值类型等。
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();
```