Skip to main content
 首页 » 编程设计

c#之将通用列表的元素添加到字典

2024年02月20日11artech

我有一个通用列表 List<String, String> ListName

我正在尝试将列表的值插入到字典中 Dictionary<String, int>

我查看了一些地方,但只发现将字典元素添加到列表中。而我的要求恰恰相反。我尝试使用 toDictionary,但它对我不起作用。不确定出了什么问题。

有没有人尝试过将列表中的值插入到字典中?

请您参考如下方法:

我假设你的意思是 List<string[]>因为我从未见过通用的 List<T,WhoAmI>之前

如果您使用 List<string[]>你可以使用 ToDictionary功能

List<string[]> ListName = new List<string[]>(); 
ListName.Add(new[] { "Stack", "1" }); 
ListName.Add(new[] { "Overflow", "2" }); 
 
// Select the first string([0]) as the key, and parse the 2nd([1]) as int 
Dictionary<string,int> result = ListName.ToDictionary(key => key[0], value => int.Parse(value[1])); 

如果您在列表中使用某种自定义对象,您也可以采用相同的方式

List<MyObject<string, string>> ListName = new List<MyObject<string, string>>(); 
Dictionary<string, int> result = ListName.ToDictionary(key => key.String1, value => int.Parse(value.String2)); 
 
 
public class MyObject<T, U> 
{ 
    public MyObject(T string1, U string2) 
    { 
        String1 = string1; 
        String2 = string2; 
    } 
 
    public T String1 { get; set; } 
    public U String2 { get; set; } 
} 

注意:您应该在 int.Parse 周围添加错误检查或使用 Int.TryParse如果有可能它可能不是数字。