c# - 如何使用 Linq where 语句动态获取另一个属性中的属性值

标签 c# asp.net-mvc linq system.reflection

我已经找到了解决这个问题的一些方向,但还没有找到任何可以应用到这个问题的方法。

我想根据它们所拥有的声明属性来过滤不同类型的列表。我可以使用 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/

相关文章:

c# - 将不同类型的ViewModel返回给 Controller

c# - 更好的 Enumerable.Range 升序和降序范围?

c# - 如何跳过最后 2 条记录并使用 linq 获取所有其他记录?

c# - 动物 thisIsACat = new Cat(); - 这是隐式转换吗?

c# - Visual Studio 2013 编辑 Razor 文件速度慢

asp.net-mvc - 为剑道网格列绑定(bind)客户端模板中的两个字段

c# - LINQ 查询除了不起作用,List<long?> 与 List<long>

c# - 使用 C# 远程连接到 SQL Server Express 2008 时遇到问题 - 但 Windows ODBC 管理员可以工作

c# - 池化的只读 SQLite 连接用于读写访问

c# - 等待多个不同的脉冲事件