C# 如何处理可能为空的列表上的排序

C# 如何处理可能为空的列表上的排序,c#,entity-framework,linq,generic-list,C#,Entity Framework,Linq,Generic List,我需要从数据库返回项目,但使用LINQ按降序返回 这是我的代码: var productItems = dbResult.ProductItems; resultObj.productItems = productItems.OrderByDescending(x => x.CreatedDate).ToList(); 我想知道如果productItems为空,如果我在可能的空列表上应用OrderByDescending,代码可能会中断吗 那么如何正确地处理这个问题呢?如果你在c#6.0

我需要从数据库返回项目,但使用LINQ按降序返回

这是我的代码:

var productItems = dbResult.ProductItems;
resultObj.productItems = productItems.OrderByDescending(x => x.CreatedDate).ToList();
我想知道如果
productItems
为空,如果我在可能的空列表上应用
OrderByDescending
,代码可能会中断吗

那么如何正确地处理这个问题呢?

如果你在c#6.0以上,你可以使用“?”操作符检查空值

如果您担心
productItems
null
,只需检查一下:

var productItems = dbResult.ProductItems;

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

这取决于您所说的列表本身是否为null,或者列表中的某个项是否为null

对于为空的列表:

if (productItems != null)
{
    // your LINQ statement
}
resultObj.productItems = productItems.Where(item => item != null).OrderByDescending(x => x.CreatedDate).ToList();
对于可能为空的项目:

if (productItems != null)
{
    // your LINQ statement
}
resultObj.productItems = productItems.Where(item => item != null).OrderByDescending(x => x.CreatedDate).ToList();

但是,此解决方案将忽略列表中的空项,除了先前回答的@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();
var productItems=dbResult.productItems;
if(productItems==null){
//设置它可以是的任何对象,例如
productItems=新列表();
}
resultObj.productItems=productItems.OrderByDescending(x=>x.CreatedDate).ToList();

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

我创建了一个快速应用程序来演示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; }
}
类程序
{
静态void Main(字符串[]参数)
{
var dbResult=新产品
{
ProductItems=新列表
{
新产品项{CreatedDate=null,ProductName=“SomeProduct”},
新的ProductItem{CreatedDate=DateTime.Now,ProductName=“SomeProduct2”},
新产品项{CreatedDate=DateTime.UtcNow,ProductName=“SomeProduct3”}
}
};
Console.WriteLine(“默认Linq排序\n”);
var result=dbResult.ProductItems?.OrderByDescending(x=>x.CreatedDate).ToList();
如果(结果!=null)
{
foreach(结果中的var productItem)
{
Console.WriteLine(“{0}创建日期:{1}\n”,productItem.ProductName,productItem.CreatedDate);
}
WriteLine(“将空排序设置为Datetime.Max\n”);
}
result=dbResult.ProductItems?.OrderByDescending(x=>x.CreatedDate??DateTime.MaxValue).ToList();
如果(结果!=null)
{
foreach(结果中的var productItem)
{
Console.WriteLine(“{0}创建日期:{1}\n”,productItem.ProductName,productItem.CreatedDate);
}
}
Console.ReadLine();
}
}
公共类产品
{
公共列表ProductItems{get;set;}
}
公共类ProductItem{
公共日期时间?CreatedDate{get;set;}
公共字符串ProductName{get;set;}
}
结果如下:

默认Linq排序

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

SomeProduct2创建日期:2019年12月2日上午10:32:58

SomeProduct创建日期:

将空排序设置为Datetime.Max

SomeProduct创建日期:

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

SomeProduct2创建日期:2019年12月2日上午10:32:58


也许可以用?@UweKeim你能写个例子吗?若列表为空,你们能写下会发生什么吗?应用。谢谢,您仍然想显示空值还是完全删除它们?您可以使用.Where()删除空值。@MarcusLai Huuum
null。OrderBy
只会抛出一个NRE,就像在包含
null
-元素的列表上抛出一个NRE一样,至少如果您使用传递给
OrderBy
@MarcusLai的委托中的任何元素成员,“如果在null列表上运行OrderbyDescending,它只会返回null”我感觉op在询问“我想知道productItems是否为null”,在这种情况下,他将得到一个nullreference异常