【问题标题】:C# LINQ - Include Where Condition only if it is not nullC# LINQ - 仅当它不为空时才包含 Where 条件
【发布时间】:2020-11-19 16:02:07
【问题描述】:

我有多个输入参数,我想在 where 子句中检查,但我只想检查参数是否为空。如果它不为 null,那么我不希望该参数出现在 where 子句中。

目前的工作方式如下:

if(userId != null){
list.Where(x=> x.Id == id && x.UserId == userId);
}
else{
list.where(x=> x.Id == id)
}

如果我们有多个可以为 null 或不为 null 的参数,这是不可行的,因为它会创建嵌套的 if 条件。这里最好的解决方案是什么?

【问题讨论】:

  • list.Where(x=> x.Id == id && (userId == null || x.UserId == userId))var query = list.where(x=> x.Id == id) 然后query = userId != null ? query.Where(x.UserId == userId) : query;

标签: c# .net linq


【解决方案1】:

你可以这样做,使用内联 if 语句:

list.Where(x =>
   (x.Id == id) &&
   (x.UserId == (userId != null) ? userId : x.UserId)
);

我不知道这是否是唯一的解决方案,但它解决了我的问题。

【讨论】:

    【解决方案2】:

    试试这个:

    list.Where(x=> x.Id == id && (userId == null || userId == x.UserId));
    

    【讨论】:

      【解决方案3】:

      我建议使用IEnumerable,在这种情况下并结合查询:

      var query = list.Where(x=> x.Id == id);
      
      if (userId != null)
      {
         query = query.Where(x => x.UserId == userId);
      }
      
      var result = query.ToList();
      

      同样的方法适用于IQueryable

      【讨论】:

        【解决方案4】:

        你可以创建一个扩展;

        public static IEnumerable<T> WhereIf<T>(
            this IEnumerable<T> source, 
            bool condition, 
            Expression<Func<T, bool>> predicate)
        {
            return condition
                ? source.Where(predicate)
                : source;
        }
        

        并像这样使用它;

        list.Where(x=> x.Id == id)
            .WhereIf(userId != null, x=> x.UserId == userId);
        

        取自https://github.com/abpframework/abp/blob/ce991482b7e83f369045073986e9c7fdd2b18534/framework/src/Volo.Abp.Core/System/Collections/Generic/AbpEnumerableExtensions.cs#L42

        还有IQueryableversion

        【讨论】:

          猜你喜欢
          • 2011-08-12
          • 2020-02-21
          • 1970-01-01
          • 2022-01-25
          • 1970-01-01
          • 2019-05-31
          • 2020-05-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多