【问题标题】:Check if no datarows returned检查是否没有返回数据行
【发布时间】:2013-12-18 11:58:06
【问题描述】:

我有这个检查与表达式匹配的数据行:

DataRow[] foundRows = this.callsTable.Select(searchExpression);

我如何检查它是否返回一些数据行,所以基本上如果它没有返回,就不要执行 if 函数中的操作?

我试过了:

if (foundRows != null) { }

【问题讨论】:

    标签: c# linq if-statement datatable


    【解决方案1】:

    您可以使用 arrayLength 属性来检查是否有任何行

    if (foundRows.Length == 0) 
    

    【讨论】:

    • 出于好奇,访问长度属性是否比调用 Count() 更快?我认为是,但我不确定。
    • @NWard Count() 尽可能优化。从the documentation如果源的类型实现ICollection<T>,则该实现用于获取元素的计数。否则,此方法确定计数。
    • Length 似乎更快,因为它不是方法,而是属性。但在我看来,它在获取过程中会执行一些操作(不仅仅是从变量中获取一些值)。所以,基本上是一样的。
    【解决方案2】:

    可以使用Count方法进行验证:

    if (foundRows.Count() == 0)
    

    【讨论】:

    • 你检查过你的解决方案了吗? foundRows是一个数组,不能使用Count方法,需要检查数组的长度。
    • 是的,Soner 是对的。 Count() 方法与属性 Count 不同。
    【解决方案3】:

    您可以使用 LINQ 执行以下操作

    var areThereAny = foundRows.Any();
    
    var count = foundRows.Count();
    

    如果您只想找出是否有任何行符合您的条件,您可以执行以下操作:

    var anyThatMatch = this.callsTable.Any(selectCondition);
    

    【讨论】:

      【解决方案4】:

      像这样检查数组的长度

         if (foundRows.Length > 0) 
         {
              //Your code here
         }
      

      或者您也可以使用 Count() 进行检查

         if (foundRows.Count() > 0)
         {
           //Your code here
         }
      

      【讨论】:

        猜你喜欢
        • 2021-11-04
        • 1970-01-01
        • 1970-01-01
        • 2014-02-15
        • 2018-07-26
        • 1970-01-01
        • 1970-01-01
        • 2021-04-16
        • 2021-08-22
        相关资源
        最近更新 更多