简体   繁体   中英

C# Update a Dictionary<string,string> with LINQ Query

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
}

Quite honestly I would prefer writing the following:

settings[setting] = value;

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.

Not only is it correct that the Value is readonly, you also should consider that the KeyValuePair itself is a struct - so the KeyValuePair you have after your query is a new instance, not a reference to the one in the Dictionary .


I'm a bit confused why you are using linq for this?

For a Dictionary<string,string> you can just use:

 settings[setting] = value

The Value of a KeyValuePair is always readonly. Note the decleration

public TValue Value { get; }

Use

settings[setting] = value;

instead. Seeing how short that is, I'm not sure what you're really gaining with this method.

There are a couple of problems with this approach.

  • The type of qry is a KeyValuePair<TKey, TValue> . This is a readonly struct which means you can't mutate it's properties.
  • Additionally since it's a struct it's a copy of the struct inside the Dictionary<TKey, TValue> . Even if you could mutate it it wouldn't update the value inside the Dictionary<TKey, TValue> and hence wouldn't have an effect

What you're looking for here is the indexer on the Dictionary<TKey, TValue> which allows for inserts of values for a given key

settings[setting] = value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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