使用此实用程序类
public static class Utility
{
//public static IEnumerable<TTarget> Where<TSource, TTarget>(this IEnumerable<TSource> source, Expression<Func<TSource, bool>> predicate) where TTarget : class, TSource
//{
// return source.Where(obj => obj is TTarget).Where(predicate.Compile()).Select(obj => obj as TTarget);
//}
public static IQueryable<TTarget> Where<TSource, TTarget>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) where TTarget : class, TSource
{
return source.Where(obj => obj is TTarget).Where(predicate).Select(obj => obj as TTarget);
}
}
例子是这样的,超类和子类就像
class Person
{
public String Name { get; set; }
public ushort Age { get; set; }
}
class Student : Person
{
public String StudentId { get; set; }
}
class Teacher : Person
{
public String TeacherId { get; set; }
}
使用该实用程序并对其进行测试
/*List of Persons*/
List<Person> persons = new List<Person>()
{
new Student(){StudentId = "Std-01", Name = "Roy", Age = 24},
new Student(){StudentId = "Std-02", Name = "Jhon", Age = 25},
new Teacher(){TeacherId = "Tch-01", Name = "Roy", Age = 24},
new Teacher(){TeacherId = "Tch-02", Name = "Jhon", Age = 25}
};
/*predictions*/
Expression<Func<Person, bool>> prediction = x => x.Name.Contains("o");
/*Use the utility*/
/*Get Teacher from Persons*/
IQueryable<Teacher> filteredItems = persons.AsQueryable().Where<Person, Teacher>(prediction);
List<Teacher> result = filteredItems.ToList();
结果我们会得到 TeacherId="Tch-01" 和 "Tch-02" 的老师
尽管我使用 IEnumerable 而不是使用 IQueryable,但希望它会有所帮助