繁体   English   中英

将结构列表转换为字典的最有效方法是什么?

[英]What is the most efficient way to convert list of structs to dictionary?

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

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);
            }

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

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

如果你放松了要求IEnumerable<string>而不是IList<string>作为值的要求,那么查找是你正在寻找的东西(内部它已实现,所以不用担心多次枚举)。

IEnumerable<mystruct> source = // ...

var lookup = x.ToLookup(c => c.key, c => c.value);
foreach (var g in lookup)
    Console.WriteLine($"Key: {g.Key}, Values: {string.Join(", ", g)}");

查找的好处是它们支持查找

var group3 = lookup[3];

,并且当使用不存在的键访问时,这将为您提供一个空序列,而不是向您抛出KeyNotFoundException

基于假设每个键有200万个密钥和20个值,已经在内存中,我就是这样做的:

var d = new Dictionary<int, List<string>>();
foreach (var s in mystruct_list)
{
    if (!d.TryGetValue(s.key, out List<string> list))
    {
        list = new List<string>();
        d[s.key] = list;
    }
    list.Add(s.value);
}

这将导致4200万字典索引读取: TryGetValue为4000万(20 * 200万),首次存储列表时加上200万个索引读取。

你的版本做了8200万个索引读取:对于20 * 200万个值中的每一个,它调用ContainsKey()mydictionary[item.key] ,这样就是20 * 2 * 200万,加上另外200万个来添加列表。

(代码应该或多或少是正确的,自从我编写c#以来已经很久了)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM