【问题标题】:How to avoid using IF-Else and use inline if condition inside the .where() function?如何避免在 .where() 函数中使用 IF-Else 并使用内联 if 条件?
【发布时间】:2021-11-30 02:12:08
【问题描述】:
 q = q.Where(s => 
                    !matchingRecords.Contains(s.Id)
                    || (s.SecId != null)
                 );

ma​​tchingrecords 可能为 null 或其中包含 0 个项目,因为它是一个列表。因此,在这种情况下,它会在上面的代码中失败。我想检查这仅包含 匹配的记录不为空,并且有一些其他元素不存在。

一种方法是放置IF-Else 块并重复代码,但我想内联,如何?

【问题讨论】:

  • q = matchingRecords?.Count() > 0 ? q.Where(s => !matchingRecords.Contains(s.Id) || (s.SecId != null) ) : q;.
  • @AluanHaddad 因为 EF 和 LINQ to SQL 被标记,?. 将不被支持。
  • @NetMage 是的,但我没有在表达式树中使用它。
  • 但原始海报是 - q 是一个 IQueryable,它构建了一个 Expression 树,因此是 EF 和 LINQ to SQL 的标签。

标签: c# entity-framework linq c#-4.0 linq-to-sql


【解决方案1】:

所以,如果输入条件是:

  • matchingRecords 不为空;
  • matchingRecords 不为空(包含元素,.Count > 0);
  • 不允许使用if-else

可以通过ternary完成吗?

var list = matchingRecords?.Count > 0 ?
           q.Where(s => !matchingRecords.Contains(s.Id) && s.SecId != null).ToList()
           : new List<Record>();

matchingRecords? 在检查“非空”后检查 null 和 .CountIf-else 替换为三进制,这将使用 Where 过滤集合或在 else 情况下返回 new List&lt;Record&gt;

示例:

class Program
{
    private static List<int> matchingRecords; // It is null, we "forget" to initialize it

    static void Main(string[] args)
    {
        var list = new List<Record>() 
        {
            new Record { Id = 0, SecId ="Some SeqId" },
            new Record { Id = 1, SecId = null },
            new Record { Id = 2, SecId = "Another SeqId" },
        };

        var filteredRecords = FilterRecords(list);
    }

    static IEnumerable<Record> FilterRecords(IEnumerable<Record> q)
    {
        return matchingRecords?.Count > 0 ? // Checking for not null and not empty (if case)
               q.Where(s => !matchingRecords.Contains(s.Id) && s.SecId != null)
               : q; // else case
    }
}

public class Record
{
    public int Id { get; set; }
    public string SecId { get; set; }
}

不确定是否正确再现了您的情况,如果有问题请纠正我。

【讨论】:

    【解决方案2】:
     q = q.Where(s => (matchingRecords != null && matchingRecords.Count > 0 && 
                    !matchingRecords.Contains(s.Id))
                    || (s.SecId != null)
                 );
    

    条件 matchingRecords != null && matchingRecords.Count > 0 将确保 !matchingRecords.Contains(s.Id) 只有在 matchingRecords 至少有 1 条记录时才会执行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      相关资源
      最近更新 更多