简体   繁体   中英

Check property of List if it is of a given type

I have this class structure

public class A
{
    int number;
}

public class B : A
{
    int otherNumber;
}

I want to search a list of A for items, where the number is greater than a given value and where the otherNumber is greater 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 list is a List<A> .

My current approach is:

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

You can filter by number field (assume fields are public). And then filter by otherNumber field if a is of B type. Otherwise second filtering will just skip

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

Maybe 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)

Select all B s that aren't bigger than 7:

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

Select all items that match the first requirement, except those that don't match the second requirement:

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

这里 - 只有B对象匹配条件,所以大多数简短形式是:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM