【问题标题】:Is null checking required for IEnumerable object?IEnumerable 对象是否需要进行空值检查?
【发布时间】:2011-05-05 05:48:45
【问题描述】:
var selectedRows = from drow in ugTable.Rows
                         .Cast<Infragistics.Win.UltraWinGrid.UltraGridRow>()
                         .Where(drow => drow != null && drow.Selected) 
                   select drow;

if(selectedRows.Count()==1){//do something with selected rows}

根据上述语句,我是否需要检查 selectedRows 的 Null 变量? selectedRows 是一个 IEnumerable 变量。

【问题讨论】:

    标签: c# .net linq linq-to-objects


    【解决方案1】:

    您无需检查selectedRows 是否为null。返回的IEnumerable&lt;&gt; 可能为空,但绝不会是null

    顺便说一句,我建议您通过编写代码来简化代码:

    var selectedRows
        = ugTable.Rows.Cast<Infragistics.Win.UltraWinGrid.UltraGridRow>()
                      .Where(drow => drow != null && drow.Selected);
    

    哪个更短且等价。

    【讨论】:

    • 太棒了.. 非常感谢 hamidi。
    • 是的! lambda 表达式比 linq 中类似 sql 的查询更好
    【解决方案2】:

    如果 where 没有匹配项,LINQ 查询将返回一个空列表(0 项)。

    因此,无需检查null

    【讨论】:

      【解决方案3】:

      在您的示例中,您可以使用扩展方法。但是,如果您要实现自己的返回 IEnumerable 的方法,答案取决于您返回结果的方式。

      以下方法返回一个空的可枚举:

      IEnumerable<object> Correct()
      {
          yield break;
      }
      

      下面的方法只返回n​​ull:

      IEnumerable<object> Incorrect()
      {
          return null;
      }
      

      调用这些方法会得到以下结果:

      Correct().Any(); // returns false
      Incorrect().Any(); // throws ArgumentNullException
      

      所以当你返回 IEnumerable 时要小心。尝试使用 yield 关键字并遵循正确的模式。

      【讨论】:

        【解决方案4】:

        我最初的感觉是不,你不,但它肯定不会受伤。

        我认为 Phil Haack 有一个有用的扩展方法,可以检查 IEnumerable 是 null 还是空...

            /// <summary>
            /// Determines whether the collection is either null or empty.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="source">The source collection.</param>
            /// <returns>
            ///     <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
            /// </returns>
            public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
            {
                return source == null || !source.Any();
            }
        

        .Any().Count() 更有效地检查是否为空

        【讨论】:

          【解决方案5】:

          Linq 不会返回 NULL 。如果你想检查一些数据,你可以去Any()

          var selectedRows = from drow in ugTable.Rows
                                   .Cast<Infragistics.Win.UltraWinGrid.UltraGridRow>()
                                   .Where(drow => drow != null && drow.Selected) 
                             select drow;
          if(selectedRows .Any())
          {
          //your code
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-07-29
            • 1970-01-01
            • 2020-05-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-09-24
            • 1970-01-01
            相关资源
            最近更新 更多