0

How to get data from array sample code below

var AllData = new Dictionary<string, object>
        {
            { "TestFun", await TestFun() },
        };
var TestFun = AllData["TestFun"] // ok
ArrayList Humidity = (ArrayList)AllData["TestFun"]; // Error
String String1= TestFun["String1"] // ???

private static async Task<Dictionary<string, object>> TestFun() { 
    var MultiArray = new  Dictionary<string, object>
        {
            { "String1", "Value1"},
        };
    return MultiArray;
}

Error

System.InvalidCastException: 'Unable to cast object of type > 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type > 'System.Collections.ArrayList'.'

Or

Cannot apply indexing with [] to an expression of type 'object'

Tried to get an answer here but couldn't find a solution...

  • 3
    Did you try `((ArrayList)AllData)["TestFun"]`? – colinD Feb 16 '23 at 07:48
  • There are no arrays in this code, much less multidimensional arrays. `AllData` is a dictionary containing the *result* of calling `TestFun()`. That method returns a `Dictionary`, not an array. The error is telling you you tried to cast that `Dictionary` to an `ArrayList`. – Panagiotis Kanavos Feb 16 '23 at 07:57
  • Whatever you want to do, this cod is a very convoluted and hard-to-read way to do it. – Panagiotis Kanavos Feb 16 '23 at 07:58
  • That's right, TestFun() returns as you say and puts it in AllData. So the question is that I can get through to the first dictionary (AllData["TestFun"]), but there is no return to from function TestFun(). but debugin ok all show. and the question is how to get through. I'm just learning, sorry for being stupid.... – Oleg Kosarev Feb 16 '23 at 08:55
  • I just need to create an array object in the TestFun() and return it and place it in the AllData. in PHP I would write the following code `function TestFun(){ return [ "String1" => "Value1" ] } $AllData= [ "TestFun" => TestFun() ]; var_dump($AllData["TestFun"]["String1"]) // Value1 ` – Oleg Kosarev Feb 16 '23 at 08:59

2 Answers2

2

TestFun() returns a Dictionary<string,object>.

System.InvalidCastException: 'Unable to cast object of type > 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type > 'System.Collections.ArrayList'.'

The exception tells you that it is not possible to cast/convert it to an ArrayList. You are trying to go from apples to monkeys.

You can either replace the type of the MultiArray variable to be an ArrayList or change the cast type to Dictionary<string,object>

Jazz.
  • 458
  • 4
  • 12
0
Dictionary<string, object> TestFun = (Dictionary<string, object>)AllData[key: "TestFun"];
string String1 = (string) TestFun["String1"];
Console.WriteLine(String1); // Value1