Use string as a property in lambda expression c#
本问题已经有最佳答案,请猛点这里访问。
我有一个将字符串和列表传递给的方法。我试图实现的是将字符串转换为lambda表达式属性。
1 2 3 4 5 6 7 | private someMethod(string myTypeString, List<Values> typeList) { foreach(var type in typeList.Where(x => x."myTypeString"> DateTime.Now)) { //do my loop } } |
有办法吗?
您可以尝试使用反射:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using System.Reflection; ... private void someMethod(string myTypeString, List<Values> typeList) { PropertyInfo pi = typeof(Values) .GetProperty(myTypeString, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | // private/internal/protected System.Reflection.BindingFlags.Public); // property exists, can be read and returns DateTime if (null == pi) return; // or throw exception else if (!pi.CanRead) return; // or throw exception else if (pi.PropertyType != typeof(DateTime)) return; // or throw exception foreach(var type in typeList .Where(x => (DateTime) (pi.GetValue(x, null)) > DateTime.Now)) { //do my loop } } |
1 2 3 4 | public static object GetPropValue(object src, string propName) { return src.GetType().GetProperty(propName).GetValue(src, null); } |
号
1 2 3 4 5 6 7 | private someMethod(string myTypeString, List typeList) { foreach(var type in typeList.Where(x => (DateTime)GetPropValue(x, myTypeString) > DateTime.Now)) { //do my loop } } |