首页 > 解决方案 > 将结构列表转换为字典的最有效方法是什么?

问题描述

我有一个由多个类型元素组成的结构,如下所示:

public struct mystruct 
{  
        int key;
        string value;  
} 

将此结构的列表转换为其键mystruct.key和值是列表的字典的最有效方法是mystruct.value什么?

我实现如下

Dictionary<int, List<string>> mydictionary = new Dictionary<int, List<string>>();
foreach (var item in mystruct_list)
            {
                if (!mydictionary.ContainsKey(item.key))
                    mydictionary.Add(item.key, new List<string>());
                mydictionary[item.key].Add(item.value);
            }

标签: c#

解决方案


假设有 mystruct 对象的集合并且键和值字段是公共的,您可以使用以下代码:

List<mystruct> myElements ... //just declaration
var result = myElements
    .GroupBy(c => c.key)
    .ToDictionary(
         c => c.Key,
         c => c.Select(i => i.value).ToList());

推荐阅读