【问题标题】:Is there a way to select a Property within a List?有没有办法在列表中选择一个属性?
【发布时间】:2019-10-24 08:48:04
【问题描述】:
class A{
 public List<B> List {get; set;}
}
class B{
 public string Property {get; set;}
}

我想写一个与此类似的 PropertyExpression: Func&lt;A, object&gt; x = y =&gt; y.List.Property

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

【问题讨论】:

  • 您想从列表的哪个元素中获取此属性?
  • 也许它适用于:.FirstOrDefault(x =&gt; x.Id == variable)。或.Single(x=&gt;x.Id...).
  • 不,我需要属性的“路径”,.FirstOrDefault() 和 .Single() 不起作用。

标签: c# list lambda reflection expression


【解决方案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 表达式。

【讨论】:

  • 遗憾的是,这不是灵魂。抱歉问了个不好的问题。我需要一个指向列表中属性的“路径”或“指针”。像Func&lt;A, object&gt; x = y =&gt; y.List.Property 这样的东西甚至没有实例化类的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 2017-04-08
  • 1970-01-01
  • 1970-01-01
  • 2023-01-01
  • 2023-03-28
  • 2019-05-06
相关资源
最近更新 更多