C#:按可为空的DateTime属性对对象列表进行排序 [英] C#: sort list of objects by DateTime property that is nullable

查看:270
本文介绍了C#:按可为空的DateTime属性对对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表:List<FakeObject> list = ...

每个对象都有一个DateTime属性,我们称它为日期"

我想按此日期属性按降序对列表进行排序.但是,当我尝试

list.Sort(new Comparison<FakeObject>((x, y) => DateTime.Compare(x.Date, y.Date)))

它抱怨,因为Date属性可以为空.

如何排序此列表,将可空日期视为MAX DATE,因此它出现在顶部?对我来说,快速简便的替代方法是不要将日期"字段设置为可空,但让我们假设现在还不能选择这种方式.

简而言之:如果DateTime可以为null,如何按DateTime对对象列表进行排序?

解决方案

一种可能的方法是:

list.Sort(new Comparison<FakeObject>((x, y) => 
    -DateTime.Compare(x.Date ?? DateTime.MaxValue,
        y.Date ?? DateTime.MaxValue)));

更新:在OP编辑问题进行澄清后修改为使用MaxDate.

请注意,您可以通过任一方式(MinDateMaxDate)执行此操作.最重要的是,如果它是null,则为其提供一些静态值即可完成所需的操作.

I have a List of objects: List<FakeObject> list = ...

Each object has a DateTime property, let's call it "Date"

I want to sort this list by this date property in descending order. However, when I try

list.Sort(new Comparison<FakeObject>((x, y) => DateTime.Compare(x.Date, y.Date)))

it complains because the Date property can be nullable.

How do I sort this list, where it treats nullable dates as MAX DATE, so it appears in the top? The quick easy alternative for me is to NOT make the Date field nullable, but let's suppose that's not an option right now.

In short: How do I sort a list of objects by DateTime, if the DateTime can be null?

解决方案

One possible approach might be:

list.Sort(new Comparison<FakeObject>((x, y) => 
    -DateTime.Compare(x.Date ?? DateTime.MaxValue,
        y.Date ?? DateTime.MaxValue)));

UPDATE: modified to use MaxDate after the OP edited the question for clarification.

Note that you could do this either way (MinDate or MaxDate). The bottom line is this, if it's null then give it some static value that accomplishes what you want.

这篇关于C#:按可为空的DateTime属性对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆