C# 更新字典使用 LINQ 查询
我正在尝试更新存储在字典中的程序设置。奇怪的是,如果它们存储在 DatabaseContext 中,以下函数将起作用(我认为),但由于它们位于字典中,我收到编译器错误。为什么我的 KeyValuePair.Value 是只读的?更重要的是,我如何重写以下函数来实际更新字典?
谢谢
public void putSetting(Dictionary<string, string> settings, string setting, string value)
{
var qry = (from s in settings
where s.Key == setting
select s).Single();
qry.Value = value; // Error 1 Property or indexer
// 'System.Collections.Generic.KeyValuePair<string,string>.Value'
// cannot be assigned to -- it is read only
}
I am trying to update my program settings, which are stored in a Dictionary. Strangely enough if they were stored in a DatabaseContext the following function would work (I think), but since they are in a Dictionary I am getting a compiler error. Why is my KeyValuePair.Value read only? More importantly, how can I re-write the following function to actually update the Dictionary?
Thanks
public void putSetting(Dictionary<string, string> settings, string setting, string value)
{
var qry = (from s in settings
where s.Key == setting
select s).Single();
qry.Value = value; // Error 1 Property or indexer
// 'System.Collections.Generic.KeyValuePair<string,string>.Value'
// cannot be assigned to -- it is read only
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
老实说,我更愿意编写以下内容:
而不是使用这个被剥夺了任何自然存在意义的
putSetting
方法。我必须承认,我在代码审查期间看到了很多事情,但这个是胜利者。Quite honestly I would prefer writing the following:
instead of having this
putSetting
method which is deprived of any natural sense for existence. I must admit that I have seen many things during code reviews but this one is a winner.Value
是只读的不仅是正确的,您还应该考虑KeyValuePair
本身是一个 struct - 因此KeyValuePair查询后得到的
是一个新实例,而不是对Dictionary
中实例的引用。我有点困惑为什么你要使用 linq 呢?
对于
Dictionary
你可以使用:Not only is it correct that the
Value
is readonly, you also should consider that theKeyValuePair
itself is a struct - so theKeyValuePair
you have after your query is a new instance, not a reference to the one in theDictionary
.I'm a bit confused why you are using linq for this?
For a
Dictionary<string,string>
you can just use:KeyValuePair
的Value
始终是只读的。请注意减法使用
代替。看到它有多短,我不确定您通过这种方法真正获得了什么。
The
Value
of aKeyValuePair
is always readonly. Note the declerationUse
instead. Seeing how short that is, I'm not sure what you're really gaining with this method.
这种方法存在一些问题。
qry
的类型是KeyValuePair
。这是一个只读结构,这意味着您无法改变它的属性。Dictionary
内结构体的副本。即使您可以对其进行变异,它也不会更新Dictionary
内的值,因此不会产生任何效果。您在这里寻找的是
上的索引器>Dictionary
允许插入给定键的值There are a couple of problems with this approach.
qry
is aKeyValuePair<TKey, TValue>
. This is a readonly struct which means you can't mutate it's properties.Dictionary<TKey, TValue>
. Even if you could mutate it it wouldn't update the value inside theDictionary<TKey, TValue>
and hence wouldn't have an effectWhat you're looking for here is the indexer on the
Dictionary<TKey, TValue>
which allows for inserts of values for a given key