Linq通过变量访问属性

Dem*_*tic 8 c# linq where

假设我有一个类:

public class Foo
{
    public string Title {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

现在,让我们假设我有一个public List<Foo> myList我想要由Linq过滤的内容:

var x = myList.Where(f => f.Title == myValue);
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很美好.

但是如何通过变量访问属性?就像是:

string myProperty = "Title";

var x = myList.Where(f => f.myProperty == myValue);
Run Code Online (Sandbox Code Playgroud)

L.B*_*L.B 18

您可以编写扩展方法

public static class MyExtensions
{
    public static object GetProperty<T>(this T obj, string name) where T : class
    {
        Type t = typeof(T);
        return t.GetProperty(name).GetValue(obj, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它

var x = myList.Where(f => f.GetProperty("Title") == myValue);
Run Code Online (Sandbox Code Playgroud)