【问题标题】:LINQ - Conditional navigation in listLINQ - 列表中的条件导航
【发布时间】:2023-03-25 00:43:02
【问题描述】:

假设我有一个继承自同一个基类的对象列表。那么是否可以通过 LINQ 获取仅在其中一个子类中指定的值?在我的示例中,我想找到具有特定对象且具有特定属性的实例?

我在 Linqpad 中做了这个例子:

void Main()
{
    var list = new List<A>
    {
        new B
        {
        MyProp = new D{ OtherProp = 1}
        },
        new C(),
        new B
        {
        MyProp = new D{ OtherProp = 30}
        },
    };

    list.Where(x => ....) // how to find the instance where OtherProp == 30 ?

}

public class A
{
    public int JustAprop { get; set; }

}

public class B : A
{
    public D MyProp { get; set; }
}

public class C : A
{

}

public class D
{
    public int OtherProp { get; set; }
}

【问题讨论】:

  • 这对我来说似乎是个错误的设计
  • 你能详细说明一下@rahul 吗?

标签: c# .net list linq


【解决方案1】:

您可以使用Where 方法并尝试将每个项目强制转换为B 类,然后OtherProp 值在MyProp

var result = list.Where(l => (l as B)?.MyProp?.OtherProp == 30);

这可以用pattern matching with is operator稍微改写

var result = list.Where(l => l is B b && b.MyProp.OtherProp == 30);

另一种方法是使用OfType&lt;T&gt; 方法仅获取B 实例的列表,然后在MyProp 中检查OtherProp

var result = list.OfType<B>().Where(b => b.MyProp.OtherProp == 30);

【讨论】:

  • 耦合太紧了..我的意思是你怎么知道B的实例的属性设置为30而不是任何其他类型的实例?
猜你喜欢
  • 2015-08-05
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多