Check the List property if it has the given type

I have this class structure

public class A
{
    int number;
}

public class B : A
{
    int otherNumber;
}

I want to find a list Afor items where numbermore than a given value and where otherNumbermore than another given value if they are of type B. I am looking for something like:

var results = list.Where(x => x.number>5 && x.otherNumber>7).ToList();

Where listthere is List<A>.

My current approach:

var results = list.Where(x => x.number>5);
foreach(var result in results)
{
    B b = result As B;
    if(b!=null && b.otherNumber>7)
        [...]
}
+4
source share
3 answers

You can filter the field number(tolerance fields are public). And then filter the field otherNumberif a is of type B. Otherwise, the second filtering will simply skip

list.Where(a => a.number > 5).Where(a => !(a is B) || ((B)a).otherNumber > 7)

Perhaps a more readable way:

list.Where(a => {
   var b = a as B;
   return a.number > 5 && (b == null || b.otherNumber > 7);
})

Or query syntax

from a in list
let b = a as B
where a.number > 5 && (b == null || b.otherNumber > 7)
+4

B, 7:

var badBs = list.OfType<B>().Where(x => x.otherNumber <= 7);

, , , :

var results = list.Where(x => x.number > 5).Except(badBs);
0

Here - only objects B will meet the condition, therefore the shortest form:

list.OfType<B>().Where(x=>x.num1 > 5 && x.num2 < 7);
0
source

Source: https://habr.com/ru/post/1568466/


All Articles