Thaadikkaaran
Thaadikkaaran

Reputation: 5226

I need to get the value from Nested Property

I need to get the value from nested property.

In MainClass i have a Students Property which is Type of Student Class.

MainClass obj = new MainClass ();

obj.Name = "XII";
obj.Students = new List<Students>()
    {
        new Students() { ID = "a0", Name = "A" },
        new Bridge() { ID = "a1", Name = "B" }
    };

Type t = Type.GetType(obj.ToString());
PropertyInfo p = t.GetProperty("Students");

object gg = p.GetValue(obj, null);
var hh = gg.GetType();
string propertyType = string.Empty;

if (hh.IsGenericType)
    {
        string[] propertyTypes = hh.ToString().Split('[');
        Type gggg = Type.GetType(propertyTypes[1].Remove(propertyTypes[1].Length - 1));
        foreach (PropertyInfo pro in gggg.GetProperties())
             {
                 if (pro.Name.Equals("Name"))
                 {
                     // Get the value here
                 }
             }
    } 

Upvotes: 1

Views: 1004

Answers (2)

SWeko
SWeko

Reputation: 30882

First of all,

Type t = Type.GetType(obj.ToString());

is wrong. This only works if a class has not overloaded the ToString() method, and will fall at runtime if it has. Fortunately, every class has a GetType() metod (it's defined on object, so Type t = obj.GetType() is the correct code.

Second, the

string[] propertyTypes = hh.ToString().Split('[');
Type gggg = Type.GetType(propertyTypes[1].Remove(propertyTypes[1].Length - 1)

is an awful way to get the type the specified the generic type, as there is a method GetGenericArguments that does that for you, so this code could be changed with

Type[] genericArguments = hh.GetGenericArguments();
Type gggg = genericArguments[0];

And now to the real problem, accessing an list item. The best way to do that is to use the indexer ([]) of the List<> class. In c# when you define an indexer, it's automatically transfered to a property called Item, and we can use that property to extract our values (the Item name can be inferred from the type definition, but for the most part, that can be hardcoded)

PropertyInfo indexer = hh.GetProperty("Item");  // gets the indexer

//note the second parameter, that's the index
object student1 = indexer.GetValue(gg, new object[]{0}); 
object student2 = indexer.GetValue(gg, new object[]{1}); 

PropertyInfo name = gggg.GetProperty("Name");
object studentsName1 = name.GetValue(student1, null); // returns "A"
object studentsName2 = name.GetValue(student2, null); // returns "B"

Upvotes: 2

abhilash
abhilash

Reputation: 5641

Override Equals method for both Students and Bridge class then use Find or use LINQ

Upvotes: 0

Related Questions