Uzair Khan
Uzair Khan

Reputation: 2970

Filtering list if date is null or not using Linq query

I have a list of objects as shown below in which date could be null,

List<SomeObjects> myList:
myList[0] = id:1, Date:3/3/2016
myList[1] = id:2, Date:NULL
myList[2] = id:3, Date:3/3/2016
myList[3] = id:4, Date:NULL

For one condition I have to sort this list as per date as shown:

var comparingDays = DateTime.Today; 
var resultsFrom = "past 7 days";
comparingDays.AddDays(-7);                      
myList.Where(t =>t.Date.HasValue ? Convert.ToDateTime(t.Date) >= comparingDays : ).ToList();

If Date is null I don't need those results, but I am struggling how to proceed in the false condition of HasValue here.

Upvotes: 0

Views: 2601

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273264

When t.Date is a DateTime (the Convert throws doubt on that), you can simply use

// myList
// .Where(t =>t.Date.HasValue ? Convert.ToDateTime(t.Date) >= comparingDays :)
// .ToList();

myList.Where(t => t.Date >= comparingDays).ToList()

Because null is not greater (or smaller) than any Date value.

Upvotes: 1

Zein Makki
Zein Makki

Reputation: 30022

A Combination of Where(filter) and OrderBy (sort) should work:

List<SomeObjects> results = myList.Where(t => t.Date.HasValue && t.Date >= comparingDays)
                                   .OrderBy(t => t.Date).ToList();

Upvotes: 2

Kinetic
Kinetic

Reputation: 2650

If "Date" is a DateTime?, you can change your query like so :

myList
  .Where(t =>t.Date.HasValue && t.Date.Value >= comparingDays).ToList()

So your null dates will be filtered and then you can safely compare the date value.

Upvotes: 3

Related Questions