有没有一种方法可以在列表中选择属性?

时间:2019-10-24 08:48:04

标签: c# list lambda reflection expression

class A{
 public List<B> List {get; set;}
}
class B{
 public string Property {get; set;}
}

我想为此编写一个类似的PropertyExpression: Func<A, object> x = y => y.List.Property

这甚至可能吗?以及如何实现呢?

1 个答案:

答案 0 :(得分:1)

您的问题不是很清楚,但希望您正在请求类似的内容。

我将按如下所示初始化对象。

您的属性:

class A{
 public List<B> List {get; set;}
}
class B{
 public string Property {get; set;}
}

            List<B> bb = new List<B>()
            {
                new B { Property = "AAA" },
                new B { Property = "BBB" }
            };

            List<A> aa = new List<A>() {
                new A {List = bb }
            };

假设您要检查是否为B类中的属性分配了一个值。

    var isExists= aa.Any(xx => xx.List[0].Property == "AAA");

同样,您可以使用任何LINQ表达式。