将 Dictionary<int, List<User>>
转换为 Dictionary<int, IEnumerable<User>>
的最有效方法是什么?
这样做的原因是我有一个构建 Dictionary<int, List<User>>
的方法,但我不想将可变的 List
返回给调用代码。
我是否必须将这本词典投影到新类型中?
最佳答案
您可以返回一个 IEnumerable
,但实际上它是一个 List
。开发人员很可能将其转换为 List
并添加或删除项目
我认为您正在寻找 Immutable Collections
简而言之,它是一个 nuget 包,使我们能够使用/创建真正不可变的集合;这意味着任何集合更改都不会反射(reflect)回公开它们的内容。
编辑:转换为 IEnumerable 不会授予不变性
鉴于 Guilherme Oliveira 的回答,可以执行以下操作并向用户添加新用户
var userDictionary = new Dictionary<int, List<User>>();
userDictionary.Add(1, new List<User>
{
new User{ Name= "Joseph"},
});
IDictionary<int, IEnumerable<User>> newDictionary = userDictionary.ToDictionary(p => p.Key, p => p.Value.AsEnumerable());
((List<User>) newDictionary.Values.First()).Add(new User {Name = "Maria"});
Console.WriteLine(newDictionary.Values.First().Count()); //now we have two users
关于c# - 转换一个 Dictionary<int, List<User>>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21909669/