我想根据外来对象类型(非值)
获取对象列表为了制作样本我只写了6个简单的类来模拟我的问题。 简而言之,我想让所有用户的活动地点都是学校的一种类型
public class User
{
public int UserId { get; set; }
public Activity Activity{ get; set; }
}
public class Activity
{
public int IdActivity { get; set; }
public Location Location { get; set; }
}
public abstract class Location
{
public int IdLocation { get; set; }
public string Xy { get; set; }
}
public class Indoor : Location
{
/// props
}
public class External : Location
{
/// props
}
public class School : Location
{
/// props
}
答案 0 :(得分:3)
只需使用is
运算符检查位置类型:
users.Where(u => u.School.Location is School)
如果某些活动可能没有位置,那么您可以使用空条件运算符来避免NullReferenceException:
users.Where(u => u.School?.Location is School)
答案 1 :(得分:1)
试试这个:
IEnumerable<User> schoolUsers = myUsers
.Where(user => user.School.Location is School);