c# - 为什么 Dictionary.Add 会覆盖我字典中的所有项目?

标签 c# linq dictionary

我有一个 Dictionary<string, IEnumerable<string>> 类型的字典和字符串值列表。出于某种原因,每次我执行添加时,字典中的每个值都会被覆盖。我完全不知道为什么会这样。我确保在循环内声明和初始化 IEnumberable 对象不是引用问题,这样它的范围就不会超出一次迭代,而且它仍然会这样做。这是我的代码:

foreach (string type in typelist)
{
    IEnumerable<string> lst = 
        from row in root.Descendants()
        where row.Attribute("serial").Value.Substring(0, 3).Equals(type)
        select row.Attribute("serial").Value.Substring(3).ToLower();

    serialLists.Add(type, lst);
}

哪里typelist是一个 IEnumerable<string> , root是一个 XElement , 和 serialLists是我的词典。

最佳答案

这是一个捕获的迭代器问题。

尝试:

foreach (string tmp in typelist)
{
   string type = tmp;

(其余不变)

或者,我会在添加期间评估表达式,即在 .Add 中执行 .ToList():

    serialLists.Add(type, lst.ToList());

第二个选项可能总体上更有效,尽管它确实强制对可能永远不需要的事物进行评估。

关于c# - 为什么 Dictionary.Add 会覆盖我字典中的所有项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10284926/

相关文章:

c# - 遍历 Linq 表达式以设置属性字段的值

c# - System.Linq.Expressions.Expression<Func<TSource,TKey>> 中的 TKey 是什么?

c++ - sets、multisets、maps 和 multimaps 如何在内部工作

c# - 可以在泛型方法中使用 IList 但不能使用 List

c# - 不同的文本渲染方法不会产生我想要的

c# - 如何在 C# Selenium 中获取表数据并将其保存在任何文档中

python-3.x - 将值累积添加到python字典

c# - Azure Functions 中 local.settings.json 的值

mysql - linq mysql : select multiple column and send the to view

ios - 无法访问字典中的键