lundi 17 octobre 2016

Compare/access object's properties dynamically with string reference

I have a simple class:

class Event {
     public string Source { get; set; }
}

Then I have a List of this class:

var list = new List<Event>();
        list.Add(new Event { Source="Me" });
        list.Add(new Event { Source="You" });

Now I want to get one Event in the list with the "Source" property set to "Me".

BUT I don't want to access this property like this list[0].Source like this:

list.Where(o => o.Source == "Me").Single()

I know that my object has the "Source" property. but I need to pass a string to get this property and compare it. Something like this:

list.Where(o => o.GetType().GetProperty("Source").GetType() == "Me").Single()

Apparently, this doesn't work. Basicaly I need to be able to write a comparison like o.Source == "ME" without referencing the property directly.

How can I do that ?





Aucun commentaire:

Enregistrer un commentaire