Linq OrderByDescending, null primero


Tengo un campo en mi base de datos que contiene una fecha y hora?. Me gustaría ordenar los resultados para que los valores NULOs aparezcan en la parte superior, luego descendiendo por Fecha y hora, por ejemplo,

null
null
2012-04-01
2012-01-01
2011-09-04

La razón es que estoy buscando fechas de vencimiento, aunque algunas entradas no caducan.

 56
Author: Frédéric Hamidi, 2011-09-03

5 answers

Puede devolver DateTime.MaxValue en lugar de null de la expresión de orden, por lo que las filas con null fechas se ordenan primero:

yourData.OrderByDescending(row => row.dateTimeField ?? DateTime.MaxValue);
 136
Author: Frédéric Hamidi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-03 06:09:05

Encuentro que el enfoque más directo es:

data.OrderBy(Function(o) o.myDate IsNot Nothing).ThenByDescending(Function(o) o.myDate)

En C# creo...

data.OrderBy(o => o.myDate != null).ThenByDescending(o => o.myDate)

Esto también funcionará con LINQ to SQL. No estoy seguro si if(nullable, value) se traducirá correctamente a SQL.

 27
Author: Zach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-17 11:04:09

Podrías intentar algo como esto:

var nulls = table.Where(x => x.NullableDateTimeField == null);
var notNulls = table.Where(x => x.NullableDateTimeField != null);

var result = nulls.Concat(notNulls.OrderByDescending(x => x.NullableDateTimeField));

Es más "obviamente correcto" que "probablemente sea súper eficiente", pero es al menos un punto de partida.

 2
Author: Jon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-03 05:59:13

Echa un vistazo a El blog de David Oesterreich:

var queryResult =
orderedProducts from enumerableProducts
order by orderedProducts.ProductName,
orderedProducts.Price != null ? 1 : 0 descending,
orderedProducts.Price
select orderedProducts;
 0
Author: andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 11:59:27

Como la versión aceptada anteriormente pero con sintaxis para c# v6

tickets.OrderByDescending(x => x?.Erstellt ?? DateTime.Now)
 0
Author: tom nobleman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-27 10:25:19