Search code examples
c#linqreflectionpropertyinfo

Using linq with a PropertyInfo


Assuming this class:

class Foo 
{
    public string Bar {get; set;}
    public string Baz {get; set;}
}

How can I use reflection to query the following list:

List<Foo> list_of_foo = new List<Foo>() 
{
    new Foo() {Bar = "Hello", Baz = "Hola"} ,
    new Foo() {Bar = "World!", Baz = "Mundo!"}
};

// match is found, and will hold the Foo with "Hello" and "Hola"
var match = list_of_foo.Single (ob => ob.Bar.Equals("Hello"));

// ------ My Question -----

// Lets assume I get the property I Need at run time:
string get_at_runtime = "Baz";
var prop_info = typeof(Foo).GetProperty(get_at_runtime);

// I can use the prop_info on the "match" variable like this:
var some_var = prop_info.GetValue(match)    // some_var holds "Hola"

// But how can I do the following: 
var some_foo = list_of_foo.Single ( f => f.prop_info.equals("Mundo!"));

Solution

  • Just:

    var some_foo = list_of_foo.Single(f => prop_info.GetValue(f).Equals("Mundo!"));
    

    but this will be safer in case of property has null value:

    var some_foo = list_of_foo.Single(f => "Mundo!".Equals(prop_info.GetValue(f)));