我已经找到了解决这个问题的一些方向,但还没有找到任何可以应用到这个问题的方法。
我想根据它们所拥有的声明属性来过滤不同类型的列表。我可以使用 linq 通过 Test.id 动态过滤列表,但我无法通过 MyClass.Name 过滤列表
我有这些类(class)。
public class Test
{
public int Id { get; set; }
public MyClass myclass { get; set; }
}
public class MyClass
{
public string Name { get; set; }
}
这就是我想要做的。
static void Main(string[] args)
{
var source = new List<Test> {
new Test { Id = 1,myclass = new MyClass() { Name = "bob" } },
new Test { Id = 2,myclass= new MyClass() { Name = "joe" } } };
var x = myFilter(source,"Name", "bob");
Console.WriteLine(x.Count());
}
public static IEnumerable<T> myFilter<T>(List<T> source, string propertyName, string searchString)
{
// get the myclass property then the stated property(Name) value within it
searchString = searchString.ToLower();
return source.Where(s => (s.GetType().GetProperty("myclass")
.GetType().GetProperty(propertyName)
.GetValue(s.GetType().GetProperty("myclass"),null).ToString() ?? " ")
.ToLower().Contains(searchString));
}
当我期望 1 时,计数返回 0。对于 Test.MyClass.Name = "bob" 有没有解决这个问题的方法,或者除了反射(reflection)之外还有更好的方法吗?
谢谢
最佳答案
您需要使用返回的 myclass
属性的 PropertyType
:
public static IEnumerable<T> myFilter<T>(List<T> source, string propertyName, string searchString)
{
// get the myclass property then the stated property(Name) value within it
searchString = searchString.ToLower();
return source.Where(s => (s.GetType().GetProperty("myclass")
.PropertyType.GetProperty(propertyName)
.GetValue(s.GetType().GetProperty("myclass").GetValue(s)).ToString() ?? " ")
.ToLower().Contains(searchString));
}
关于c# - 如何使用 Linq where 语句动态获取另一个属性中的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41758741/