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

How to dynamically get a property value in which is in another property with Linq where statement

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

我想根据所声明的属性来过滤不同类型的列表。我可以使用 linq 按 Test.id 动态过滤列表,但我无法通过 MyClass.Name

过滤列表

我有这些类。

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));
}

计数 return 0 当我期待 1. 用于测试。MyClass.Name = "bob" 有没有解决这个问题的方法,或者除了反射之外还有更好的方法吗?

谢谢

你需要使用返回的 myclassPropertyType 属性:

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));
}

您应该可以使用以下内容:

var count = source.Count(test => 
                             string.Compare(test.myClass.Name, "Bob", 
                                        StringComparison.CurrentCultureIgnoreCase) == 0);

这将比较 Name 属性 的字符串值,只计算名称等于 "bob" 的地方,它会忽略大小写。

如果你想 return 测试对象,那么你可以使用下面的

var results = source.Where(test => 
                             string.Compare(test.myClass.Name, "Bob", 
                                        StringComparison.CurrentCultureIgnoreCase) == 0);