如何在where子句中使用LINQ Except()

时间:2014-03-27 21:54:20

标签: c# linq where

我无法理解如何正确使用Except()。 我想在 where子句中使用Except()来排除与字符串列表匹配的结果。我编写了下面的小例子来说明。

另外,在这种情况下使用Except是最快的方法吗?如果不是,那会更快?

我有这个:

var result = (from FunTable in Context.t_FunTable

              where FunTable.ft_FunStartDate >= startDate
              && FunTable.ft_FunEndDate <= endDate

       ---->  && FunTable.ft_FunStage != notAllowedStage1 
       ---->  && FunTabble.ft_FunStage != notAllowedStage2

              select FunTable.ActivityName).ToList<String>();

我想这样做:

var result = (from FunTable in Context.t_FunTable

              where FunTable.ft_FunStartDate >= startDate
              && FunTable.ft_FunEndDate <= endDate

      ---->   && FunTable.ft_FunStage.Except(ListOfNotAllowedStages)

              select FunTable.ActivityName).ToList<String>();

3 个答案:

答案 0 :(得分:5)

您可以改为使用Contains

!ListOfNotAllowedStage.Contains(FunTable.ft_FunStage)

Any

!ListOfNotAllowedStage.Any(x => x == FunTable.ft_FunStage)

答案 1 :(得分:3)

在我看来你想要这个:

&& !ListOfNotAllowedStages.Contains(FunTable.ft_FunStage)

答案 2 :(得分:2)

最佳解决方案由Selman22中的his answer提供,但要直接回答问题,必须注意Except方法是not supported by the query syntax。所以,如果你真的想使用Except,你必须尝试这样的事情:

var result = (from FunTable in Context.t_FunTable
              where FunTable.ft_FunStartDate >= startDate
              && FunTable.ft_FunEndDate <= endDate)
             .Except(Context.t_FunTable
                 .Where(x => ListOfNotAllowedStages.Contains(x.ft_FunStage))))
             .Select(x => x.ActivityName);

正如您所看到的那样有点复杂,因此这不是解决此问题的最佳方法。如Selman22所示,在!ListOfNotAllowedStage.Contains(FunTable.ft_FunStage)子句中添加简单条件where是最佳解决方案。

相关问题