Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am having one property called Students which is of type List<Student>.

In reflection i can get the value of Students Property.

Now the problem is How to iterate the List of Students.

I need to check whether StudentID [ some value ] is in that collection.

var collection = studentPro.GetValue(studentObj,null);

//I need to iterate like this,

foreach(var item in collection)
{
     if(item.StudentID == 33)
         //Do stuff
}

Please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
211 views
Welcome To Ask or Share your Answers For Others

1 Answer

You just need to cast it:

var collection = (List<Student>) studentPro.GetValue(studentObj,null);

The value returned to you and stored in var is of type object. So you need to cast it to List<Student> first, before trying looping through it.

RANT

That is why I personally do not like var, it hides the type - unless in VS you hover on it. If it was a declared with type object it was immediately obvious that we cannot iterate through it.


UPDATE

Yes its good. But casting should be done with reflection. In reflection we dont know the type of List. We dont know the actual type of the studentObj

In order to do that, you can cast to IEnumerable:

var collection = (IEnumerable) studentPro.GetValue(studentObj,null);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...