IDictionary in .NET 4 not covariant

It’s a feature. .NET 4.0 only supports safe covariance. The cast you mentioned is potentially dangerous as you could add a non-string element to the dictionary if that was possible: IDictionary<string, object> myDict = new Dictionary<string, string>(); myDict[“hello”] = 5; // not an string On the other hand, IEnumerable<T> is a read-only interface. The T … Read more

How to insert values into VB.NET Dictionary on instantiation?

If using Visual Studio 2010 or later you should use the FROM keyword like this: Dim days = New Dictionary(Of Integer, String) From {{0, “string”}, {1, “string2”}} See: If you need to use a prior version of Visual Studio and you need to do this frequently you could just inherit from the Dictionary class … Read more

Dictionary merge by updating but not overwriting if value exists

Just switch the order: z = dict(d2.items() + d1.items()) By the way, you may also be interested in the potentially faster update method. In Python 3, you have to cast the view objects to lists first: z = dict(list(d2.items()) + list(d1.items())) If you want to special-case empty strings, you can do the following: def mergeDictsOverwriteEmpty(d1, … Read more

groovy: safely find a key in a map and return its value

The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false, then you can do this: def mymap = [name:”Gromit”, likes:”cheese”, id:1234] def key = “likes” if(mymap[key]) { println mymap[key] } However, if the value could potentially be Groovy-false, you should use: … Read more

Get first key from Dictionary

Assuming you’re using .NET 3.5: dic.Keys.First(); Note that there’s no guaranteed order in which key/value pairs will be iterated over in a dictionary. You may well find that in lots of cases you get out the first key that you put into the dictionaries – but you absolutely must not rely on that. As Skirwan … Read more