Reputation: 7525
I need to check if a key exists and accordingly to an add or an update in the dictionary.
if (dict.ContainsKey("Key1"))
dict["Key1"] = "Value1";
else
dict.Add("Key1", "Value1");
Can I simplify this using Linq or otherwise?
Upvotes: 0
Views: 5631
Reputation: 7203
You can also use something like this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("1", "1");
dict.Add("2", "2");
var x = dict.Where(q => q.Key == "1");
if (x.Any())
dict[x.FirstOrDefault().Key] = "new";
Upvotes: 0
Reputation: 2752
Not really...linq is a query language and is not intended to mutate data structures. You can sort of get around this, but you shouldn't consider your code wrong just because it isn't linq. The only line you could add to the code you posted to 'linq-ify' it would be to change dict.ContainsKey("Key1")
to dict.Any(x => x.Key == "Key1")
, but don't do this as it will no doubt be slower. I actually think Darin's answer is quite elegant and recommend you use it!
Upvotes: 0
Reputation: 1038850
You can simplify your 4 lines of code to this:
dict["Key1"] = "Value1";
If Key1 doesn't exist in the dictionary it will be added and if it exists the value will be updated. That's what the indexer does. As far as LINQ is concerned I don't see any relation to the question.
Upvotes: 8