The neat method would be to separate your LINQ query from the way you define which item comes before another item. In other word: what is the sort order of Item X and Item Y
For this we need to create a class that implements IComparer<Item>
class Item
{
public Announcement Announcement {get; set;} // your inner object, might be null
...
}
class Announcement
{
public DateTime CreatedDate {get; set;}
...
}
Suppose you you have two Items
, one of them has a null Anouncement
.
Item item1 = new Item {Announcement = null};
Item item2 = new Item {Announcement = new AnnounceMent{CreatedDate=new DateTime(2000, 1, 1)}};
It's up to you to decide which comes first. Let's assume you want the null items at the end.
class ItemComparer : Comparer<Item>
{
public static readonly ByCreatedDate = new ItemComparer();
private static readonly IComparer<DateTime> dateComparer = Comparer<DateTime>.default;
public override int CompareTo(Item x, Item y)
{
// TODO: decide what to do if x or y null: exception? comes first? comes last
if (x.Announcement == null)
{
if (y.Announcement == null)
// x and y both have null announcement
return 0;
else
// x.Announcement null, y.Announcement not null: x comes last:
return +1;
}
else
{
if (y.Announcement == null)
// x.Announcement not null and y.Announcement null; x comes first
return -1;
else
// x.Announcement not null, y.Announcement not null: compare dates
return dateComparer.CompareTo(x.CreatedDate, y.CreateDate)
}
}
}
Usage:
(improved after comment by Peter Wurzinger)
var result = items.OrderByDescending(item => item, ItemComparer.ByCreatedDate);
Note: If you decide to change the sort order of your Items, all you have to do is change the ItemComparer class. All your LINQ statements that order your Items will then use the new sort order.