How to use dynamic field name in where statement?
example: I can use,
MyList.Where(x => x.Name == "MyName");
but how to use like this?
string MyField = "Name";
MyList.Where(x => MyField == "MyName");
You could use PropertyInfo
from System.Reflection
and use its GetValue()
method :)
PropertyInfo inf = typeof(YourClass).GetProperty("PropertyName");
MyList.Where(x => inf.GetValue(x) == "MyName");
For it to work, of course the variable Name
should be a Property
like so :
public string Name { get; set; }
Hope it helped :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.