I've been struggling to Google this question as I can't get the wording quite right (hence the title).
The gist is why do one of the below work, is there a shorthand for test3:
var test1 = new Dictionary<string, int>(); test1["Derp"] = 10; // Success var test2 = new Dictionary<string, List<int>>(); test2["Derp"].Add(10); // Fail var test3 = new Dictionary<string, List<int>>(); test3["Derp"] = new List<int>(); test3["Derp"].Add(10); // Success A scenario I'm coming across often is similar to the below (this is a very basic example):
var names = new List<string>() { "Jim", "Fred", "Fred", "Dave", "Jim", "Jim", "Jim" }; var nameCounts = new Dictionary<string, int>(); foreach(var name in names) { if (!nameCounts.ContainsKey(name)) nameCounts.Add(name, 0); nameCounts[name]++; } In other words - is there a way to skip the "ContainsKey" check, and go straight to adding to my list (and key automatically)?
Edit: to be clear, I hadn't used the below as in my real-life situation, it isn't quite as simple (unfortunately!)
var nameCounts = names.GroupBy(x => x) .ToDictionary(x => x.Key, x => x.Count());
TryGetValuerather thanContainsKey. The general pattern I would recommend is dotnetfiddle.net/jPGk8E . Or considerMultiValueDictionary- github.com/dotnet/corefx/issues/1306 .var nameCounts = names.GroupBy(x=>x).ToDictionary(x=>x.Key, x=>x.Count());Add, andGetand so on, that I needed. It made the resulting code easy to write and read.