Why if I have a Dictionary<string, MyClass> myDic
in C# I can't do
myDic.Values[1]
because it can't index a Dictionary instead of Vb.Net that allow me to do
myDic.Values(1)
? Is there any difference between C# Dictionary and a VB.Net one?
Asked
Active
Viewed 186 times
0

CRK
- 337
- 2
- 10
-
4`myDic.Values.ElementAt(0)` if you want the very 1st item of the `Values`; however the order in `Values` is undefined in case of Dictionary – Dmitry Bychenko Oct 27 '16 at 15:22
-
@DmitryBychenko so Vb.Net allow you to apply indexing and C# not? – CRK Oct 27 '16 at 15:42
-
Vb.Net provides the syntax, but it's completely misguiding, since the order is not guaranteed. – Dmitry Bychenko Oct 27 '16 at 15:45
-
@DmitryBychenko where can I found in .Net Framework where this is defined? – CRK Oct 27 '16 at 15:47
-
1https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,c86f0825c2db4ec0 – Dmitry Bychenko Oct 27 '16 at 15:53
1 Answers
4
No, the short answer is that you cannot apply an indexing to a C# Dictionary<>.ValueCollection.
As mentioned in the comments below, the closest C# correlation is using myDict.Values.ElementAtOrDefault(1)
to retrieve the value, since it will safely return the default if the value is not present, which matches the VB.Net behavior. That said, this may be indicative of misusing a dictionary, particularly since order is not guaranteed.
Typically, the most efficient and valuable way to retrieve values from a Dictionary is by key lookup. This is merely speculation, but it wouldn't surprise me if indexing on the Values Collection was not supported in C# simply to guide you in the right direction and prevent abuse.

David L
- 32,885
- 8
- 62
- 93
-
-
1@CRK correct. And in my opinion this is actually a C# feature and a much better approach than what VB provides since it is more consistent with the behavior of the collection. – David L Oct 27 '16 at 15:44
-
Good answer, but to be absolutely identical you should use 'ElementAtOrDefault' since in these cases VB will allow you to use indexing on an empty dictionary and will yield the default value of the ValueCollection (or KeysCollection). That is, VB is actually calling 'ElementAtOrDefault' behind the scenes, not 'ElementAt'. – Dave Doknjas Oct 27 '16 at 21:41
-
@DaveDoknjas how do u know that he's calling ElemenAtOrDefault? Just for curiosity – CRK Oct 28 '16 at 07:45
-
1@CRK: Because that's what VB is calling when you use indexing on a 'ValueCollection' (or 'KeyCollection'). I've tested it and indexing yields the default value for the type when the dictionary is empty, which would not happen if VB were calling 'ElementAt'. – Dave Doknjas Oct 28 '16 at 14:40
-
1@DaveDoknjas great information, thank you. I wasn't aware of VB applying the ElementAtOrDefault extension to the ValuesCollection, but it absolutely does in a simple LinqPad example. I've updated my answer to reflect your comments. – David L Oct 28 '16 at 14:48