如何在c#中使用谓词来避免和/或条件

时间:2018-01-15 10:17:11

标签: c# linq

var queryableDcbooking = (from t in dcBookingEntities.Bookings
  join t1 in dcBookingEntities.BookingWorkFlowStatusMasters on t.BookingWorkFlowStatusId equals t1.BookingWorkFlowStatusId
  join t2 in dcBookingEntities.StatusMasters on t.StatusId equals t2.StatusId
  join t3 in dcBookingEntities.PNBStatusMasters on t.PNBStatusId equals t3.PNBStatusId into gj
  from pnb in gj.DefaultIfEmpty()
  where (
  (paraName.ToLower() == Comparator.Bookingid && intSearch.Contains(t.BookingId))
  || (paraName.ToLower() == Comparator.Dccode && strSearch.Contains(t.DCMaster.DCCode))
  || (paraName.ToLower() == Comparator.Supplierid && intSearch.Contains(t.SupplierId))
  || (paraName.ToLower() == Comparator.Doorid && intSearch.Contains(t.DoorId))
  || (paraName.ToLower() == Comparator.Carrierid && intSearch.Contains(t.CarrierId))
  || (paraName.ToLower() == Comparator.Buyer && strSearch.Contains(t.Buyer))
  )

paraNamebookingIddccode字符串搜索,intSearch包含多个bookingids

我可以在Linq查询中使用谓词来避免和/或使用谓词中的条件吗?

1 个答案:

答案 0 :(得分:4)

您可以在确定要使用的参数的方法中构建表达式:

private Expression<Func<Foo, bool>> GetExpression(string param, string searchTerm)
{
    switch (param)
    {
        case "bar":
            return f => f.Bar.Contains(searchTerm);
        case "baz":
            return f => f.Baz.Contains(searchTerm);
        // ...
    }
}

然后这样称呼:

var bars = (from c in collection select c).Where(GetExpression(param, searchTerm));