0

I want to add "_new" to the existing value if a key is present in the Dictionary object else want to keep it blank.

I have a dictionary object

"LanguageMapping": {
    "LanguageMappingCode": {
      "en-CA": "ca-en",
      "fr-CA": "ca-fe",
      "ab-GB": "gb-ab",  
.....so on    
    }
  }

I am using Linq to fetch the value from key.

_languageMapping.LanguageMappingCode.FirstOrDefault(x => x.Key == LanguageCode)Value

Currently, I am getting a response as "ca-en" if I pass key "en-CA" but I want a response as "ca-en_new".

Is it possible to achieve using Linq?

user2148124
  • 940
  • 1
  • 7
  • 20
  • Does this answer your question? [How to update the value stored in Dictionary in C#?](https://stackoverflow.com/questions/1243717/how-to-update-the-value-stored-in-dictionary-in-c) – Sinatr Jul 12 '21 at 10:18
  • I want to achieve something like dict[key] = value + newValue but using Linq and at run time – user2148124 Jul 12 '21 at 10:22
  • Not easily, without creating a new dictionary (which seems an expensive operation). Does the value in the dictionary need to change, or the value you use? If the latter, just append `_new` to the `Value` you get from the dictionary – Martin Jul 12 '21 at 10:22
  • @Martin here can we do something with Value of Linq without using + or append? _languageMapping.LanguageMappingCode.FirstOrDefault(x => x.Key == LanguageCode)Value – user2148124 Jul 12 '21 at 10:24
  • There is [this answer](https://stackoverflow.com/a/31073047/1997232) in duplicate. – Sinatr Jul 12 '21 at 10:25
  • @user2148124 You will ultimately have to use `+ "_new"` or append even if you do it in pure Linq. How else would you make the new string? – Martin Jul 12 '21 at 10:26

1 Answers1

0

I'm not clear on whether you just want to modify the value you use from the Dictionary, or whether you want to update all of the values in the Dictionary (or something else).

This will create a new Dictionary that has _new appended to every value:

var newDict = _languageMapping.LanguageMappingCode.ToDictionary(item => item.Key, item => item.Value + "_new");

This is an expensive operation.

Otherwise you can just append _new to the value before you use it:

var value = _languageMapping.LanguageMappingCode.FirstOrDefault(x => x.Key == LanguageCode).Value + "_new";
Martin
  • 16,093
  • 1
  • 29
  • 48