How can I get the Lists inside an Object? c#

1.1k Views Asked by At

I have this object:

Object
 Adress - count = 2 - System.Collections.Generic.List<Address>
  [0]   Address
    City - "Text" - string
    State - "Text" - string
  [1]   Address
    City - "Text" - string
    State - "Text" -string
 Notes - "Text" - string
 Items - Type(Item)
  Item - count = 2 - System.Collections.Generic.List<Item>
   [0]  Item
    Name - "Text" - string
    Price - "Text" - string
   [1]  Item
    Name - "Text" - string
    Price - "Text" - string

In this object, Address is a list of all addresses, notes is just another field of the object and items has a child named item and it contains Lists inside, just like address.

I am getting the value of notes by this code:

foreach (var item in (object as IEnumerable).Cast<object>().ToList())
                    {
    String substring = item.GetType().GetProperty("Notes").GetValue(item).ToString();
}

This is the return I get from the method when it passes to List:System.Collections.Generic.List1[Address]

But I can't access the lists, I need to separate this object in X Lists, like this:

Object2
 Adress
  [0]
  [1]

Object3
 Items
  Item
   [0]
   [1]

And then I can get the values using the method above, any suggestions? I already tried so many ways...

1

There are 1 best solutions below

6
On

Just cast the value of Adress property to List<Object>, like this

foreach (var item in (object as IEnumerable).Cast<object>().ToList())
{
    List<Object> address = item.GetType().GetProperty("Adress").GetValue(item) as List<Object>;
    foreach(var ad in address)
    {
        //do what you want here
    }
}