c# - 将结构列表转换为字典的最有效方法是什么?
问题描述
我有一个由多个类型元素组成的结构,如下所示:
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());
推荐阅读
- python - 在 Rstudio 或 Jupyter notebook 等浏览器中访问 Python Spyder(非 SSH)
- c++ - C++:为什么要为非析构函数的纯虚函数提供定义(而不是覆盖)?
- unit-testing - Dart 中的单元测试文本输出 (stdout.write/print)
- macos - 为什么“macOS 文件夹存档”没有使用 install4j 签名
- python - python vs matlab中的特征值和特征向量
- javascript - 动画变慢
- android - 如何从 FragmentActivity 显示 CustomDialog
- c# - 锐化操作,输出对比度不正确
- ios - AVAssetWriter 在追加缓冲区时因内存问题而终止
- javascript - 电子:无法读取未定义的属性“on”