Why Dictionary "does not contain a definition for 'ElementAt'"?

Why Dictionary "does not contain a definition for 'ElementAt'" during dynamic programming

        Dictionary<string, dynamic> D1 = new Dictionary<string, dynamic>();
        D1.Add("w1", 10);
        D1.Add("w2", false);
        Dictionary<string, dynamic> D2 = new Dictionary<string, dynamic>();
        D2.Add("v1", 10);
        D2.Add("v2", D1);
        textBox1.Text += D2.ElementAt(1).Value.ElementAt(1).Value;

we should get result on textbox1 "false"
But instead we will get run-time error: "does not contain a definition for 'ElementAt'"

if you will type:

        Dictionary<string, dynamic> var1 = D2.ElementAt(1).Value;
        textBox1.Text += var1.ElementAt(1).Value;

Then it will work correctly!

Jon Skeet
people
quotationmark

There are two things wrong here:

  • You're assuming that the second entry you added to D2 is the one retrieved by D2.ElementAt(1). Don't make that assumption: dictionaries are basically unordered.
  • You're calling an extension method (Enumerable.ElementAt) on an expression of type dynamic

You can fix the second problem by just explicitly calling Enumerable.ElementAt as a static method:

textBox1.Text += Enumerable.ElementAt(D2.ElementAt(1).Value, 1).Value;

This will still leave the first part as a problem though. It's not clear what you're trying to achieve, which means it's not clear what fix I should be suggesting to that part...

people

See more on this question at Stackoverflow