Cannot cast object type to representative class with same properties

48 Views Asked by At

I have an ExpandoObject (recordValue in this example) that I traverse through and I need to extract the value for given key. For that purpose, I do the following:

var objectValue = recordValue.Where(x => x.Key == objId).Select(x => x.Value).FirstOrDefault();

This returns me a type object and if I check the value of the object in a debug mode, I get the following data:

Count=2:
[0] = "random string" (of type string)
[1] = Count = 3 {(1, 2, 3)} (of type List<long>)

I made a class named Info that has two properties, the first one string and the second one list:

public class Info
{
  public string Value { get; set; }
  public List<long> List { get; set; }
}

C# says that the type is object so I tried to cast via (Info) objectValue but then I get an error that Generic.List``1(System.Object) cannot be casted into Info. I tried to cast it into a List<Info> but still no luck. Since it says that it's a List<System.Object>, I tried to iterate it but this time I got an error that object has no method Count. I tried to get the values by passing index to objectValue but still getting an error that indexing is not allowed on type object.

This got me so confused and I don't know whether my variable is object or List<System.Object> and I cannot find a way to cast the value into my class Info.

What am I doing wrong and how can I cast this object into my Info? If not possible, at least how can I extract the string and the list from objectValue?

0

There are 0 best solutions below