【问题标题】:How to handle ordering on possible null list如何处理可能的空列表上的排序
【发布时间】:2019-12-02 15:06:19
【问题描述】:

我需要使用 LINQ 以降序从数据库返回项目。

这是我的代码:

var productItems = dbResult.ProductItems;
resultObj.productItems = productItems.OrderByDescending(x => x.CreatedDate).ToList();

我想知道如果productItems 为空,如果我在可能的空列表上应用OrderByDescending,代码可能会中断吗?

那么如何正确处理呢?

【问题讨论】:

  • 也许使用?. operator
  • @UweKeim 你能写例子吗?如果列表为空但是你能写出会发生什么吗?被申请;被应用。谢谢老哥
  • 您还想显示空值还是完全删除它们?您可以使用 .Where() 删除空值。
  • @MarcusLai Huuum? null.OrderBy 只会抛出一个 NRE,OrderBy 在包含 null-elements 的列表上也会抛出一个 NRE,至少如果您使用传递给 OrderBy 的委托中的任何元素成员。
  • @MarcusLai “如果你在一个空列表上运行 OrderbyDescending,它只会返回空”会得到一个空引用异常

标签: c# entity-framework linq generic-list


【解决方案1】:

如果您担心productItemsnull,只需检查一下即可:

var productItems = dbResult.ProductItems;

if (productItems != null)
{
    resultObj.productItems = productItems.OrderByDescending(x => x.CreatedDate).ToList();
}

【讨论】:

    【解决方案2】:

    除了之前回答的@robbpriestley:

    如果您不希望您的 ProductItems 为空,您可以在订购列表之前设置一个空的默认值:

    var productItems = dbResult.ProductItems;
    if (productItems == null) {
        // Set whatever object it can be, such as
        productItems = new List<object>();
    }
    
    resultObj.productItems = productItems.OrderByDescending(x => x.CreatedDate).ToList();
    

    这样,您仍然会得到一个项目列表(或您正在使用的任何实体),但它会是空的。

    【讨论】:

      【解决方案3】:

      这取决于您是在谈论列表本身为空还是该列表中的项目为空。

      如果列表为空:

      if (productItems != null)
      {
          // your LINQ statement
      }
      

      对于可能为 null 的项目:

      resultObj.productItems = productItems.Where(item => item != null).OrderByDescending(x => x.CreatedDate).ToList();
      

      但是,这个解决方案会忽略列表中的空项,它们不会在resultObj.productItems

      【讨论】:

        【解决方案4】:

        我创建了一个快速应用程序来展示 linq 如何处理空项目的排序。就像其他一些海报所建议的那样,您也应该检查列表是否为空。

        class Program
        {
            static void Main(string[] args)
            {
                var dbResult = new Product
                {
                    ProductItems = new List<ProductItem>
                    {
                        new ProductItem {CreatedDate = null, ProductName = "SomeProduct"},
                        new ProductItem {CreatedDate = DateTime.Now, ProductName = "SomeProduct2"},
                        new ProductItem {CreatedDate = DateTime.UtcNow, ProductName = "SomeProduct3"}
                    }
                };
        
                Console.WriteLine("Default Linq Ordering\n");
        
                var result = dbResult.ProductItems?.OrderByDescending(x => x.CreatedDate).ToList();
        
                if (result != null)
                {
                    foreach (var productItem in result)
                    {
                        Console.WriteLine("{0} Created Date: {1} \n", productItem.ProductName, productItem.CreatedDate);
                    }
        
                    Console.WriteLine("Set null ordering to Datetime.Max\n");
                }
        
                result = dbResult.ProductItems?.OrderByDescending(x => x.CreatedDate ?? DateTime.MaxValue).ToList();
                if (result != null)
                {
                    foreach (var productItem in result)
                    {
                        Console.WriteLine("{0} Created Date: {1} \n", productItem.ProductName, productItem.CreatedDate);
                    }
                }
        
                Console.ReadLine();
            }
        }
        
        public class Product
        {
            public List<ProductItem> ProductItems { get; set; }
        }
        public class ProductItem {
            public DateTime? CreatedDate { get; set; }
        
            public string ProductName { get; set; }
        }
        

        输出如下:

        默认 Linq 排序

        SomeProduct3 创建日期:2019 年 12 月 2 日下午 3:32:58

        SomeProduct2 创建日期:12/2/2019 10:32:58 AM

        SomeProduct 创建日期:

        将空排序设置为 Datetime.Max

        SomeProduct 创建日期:

        SomeProduct3 创建日期:2019 年 12 月 2 日下午 3:32:58

        SomeProduct2 创建日期:12/2/2019 10:32:58 AM

        【讨论】:

          【解决方案5】:

          如果你在 c# 6.0 以上,你可以使用 '?'运算符检查 null https://csharp.today/c-6-features-null-conditional-and-and-null-coalescing-operators/

          【讨论】:

            猜你喜欢
            • 2017-07-17
            • 1970-01-01
            • 2013-10-10
            • 2021-08-19
            • 2013-04-19
            • 1970-01-01
            • 2015-10-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多