Q:

LINQ - Conditional navigation in list

Let's say I have a list of objects which inherits from the same base class. Is it then possible to get the value that is only specified in one of the subclasses through LINQ? In my example, i want to find the instance which has a specific object which has a specific property?
I have made this example in 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; }
}

A:

You can use Where method and try to cast every item to B class, then OtherProp value inside MyProp
var result = list.Where(l => (l as B)?.MyProp?.OtherProp == 30);

This can be rewritten a little bit using pattern matching with is operator
var result = list.Where(l => l is B b && b.MyProp.OtherProp == 30);

Another way is to use OfType<T> method to get a list of B instances only, then check OtherProp inside MyProp
var result = list.OfType<B>().Where(b => b.MyProp.OtherProp == 30);

