开发者

Adding or updating dictionary elements using Linq

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 t开发者_高级运维his using Linq or otherwise?


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.


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!


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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜