【发布时间】:2018-07-17 15:08:42
【问题描述】:
假设我有两个班级:
public class Parent {
public Child Child { get; set; }
}
public class Child {
public string Name { get; set; }
}
我想编写一个函数,通过包含子字符串的孩子的名字过滤父母。
public IQueryable<Parent> ParentsChildNameMatches(IQueryable<Parent> parents, string word)
{
return parents.Where(parent => parent.Child.Name.Contains(word));
}
如果我想取出那个表达式,以便我可以在其他地方重用 Child contains 检查
public Expression<Func<Child, bool> ChildNameMatches(string word)
{
return child => child.Name.Contains(word));
}
然后如何在我的 .Where 中使用它以便我可以重写 ParentChildNameMatches?
public IQueryable<Parent> ParentsChildNameMatches(IQueryable<Parent> parents, string word)
{
return parents.Where( // how to leverage ChildNameMatches?
}
【问题讨论】:
-
其实,你的
ChildNameMatches不应该接受Parent,而不是Child,而是return parent => parent.Child. ...吗? -
好吧,我的目标是,我可以自己重用 ChildNameMatches 表达式,用于 Child 类,或者当有其他具有 Child 属性的父类时。
-
如果在
Child类中定义了特定方法ChildNameMatches,那么您可以添加另一个具有我为Parent类建议的签名的方法,否则您将无法直接在.Where()调用中使用它。
标签: c# lambda expression iqueryable