Linq可选ORing(方法语法)

本文关键字:语法 方法 可选 ORing Linq | 更新日期: 2023-09-27 18:22:24

如何将这两个方法合并为一个?

public override Expression<Func<Attachment, bool>> MatchingCriteria
{
  get { return a => a.Activity.Parent.ActivityUsers.Any(x => (x.User.Id == id)); }
}

public override Expression<Func<Attachment, bool>> MatchingCriteria
{
  get { return a => a.Activity.ActivityUsers.Any(x => (x.User.Id == id)); }
}

值得注意的是,我想检查根记录中是否有指向某个用户的链接。但是,a可能是根,也可能是子(仅限一个分散/级别;不递归)。我想要一个ORing,可以说,这两个林克表达。

Linq可选ORing(方法语法)

也许类似于:

public override Expression<Func<Attachment, bool>> MatchingCriteria
{
  get 
  {
     return a => a.Activity.Parent.ActivityUsers
                  .Concat(a.Activity.ActivityUsers).Any(x => (x.User.Id == id));
  }
}

或者,由于你只担心一个级别的深度,你可能会使用:

public override Expression<Func<Attachment, bool>> MatchingCriteria
{
  get 
  {
     return a => a.Activity.Parent.Any(a2 => 
         a2.ActivityUsers.Any(x => 
             (x.User.Id == id) || x.Activity.ActivityUsers.Any(y =>
                 y.User.Id == id)));
  }
}

这个选项可能更合适。

public override Expression<Func<Attachment, bool>> MatchingCriteria
{
  get { return a => a.Activity.Parent.ActivityUsers.Any(x => (x.User.Id == id)) 
                 || a.Activity.ActivityUsers.Any(x => (x.User.Id == id)); 
      }
}