DateTime filter

I have been trying to optimize the filtering process of a Collection<Alert> based on the DateTime GeneratedOn property of Alert class.

Below is the code block which filters the List by taking in From Date and To Date.

if (this.Alerts != null)
{

if (fromDt > toDt)
{
Messages.InfoMessage("FromDate cannot be greater than ToDate", "Alert"); return;
}
this.IsBusy = true;
var filteredAlerts = this.Alerts.Where(a => (DateTime.Parse(a.Created) >= fromDt) && (DateTime.Parse(a.Created) <= toDt));
this.IsBusy = false;
}


Is there a better way of doing this?

-
You mean you're trying to make this code faster? Did profiling tell you this code is really a bottleneck in your application? –  svick Aug 21 '12 at 10:28
But my primary advice would be to try to avoid strings for representing dates and times as much as possible. Certainly don't use them to combine a date with a time, that will be slow and unreliable. –  svick Aug 21 '12 at 10:35
I want a very precise filtering that can even filter out records based on time, that's why I combined the Date and Time, by converting it to ToShortDateString() and ToLongTimeString(). –  syyad Aug 21 '12 at 12:00
Yeah, but I don't see any reason why you would use strings for that. You should work only with the DateTimes directly. –  svick Aug 21 '12 at 17:49

Why are you storing FromDate and FromTime seperately to begin with?

Instead of storing using four properties, use only two, storing both Date and TimeOfDay inside them:

public DateTime FromAlert { get; private set; }
public DateTime ToAlert { get; private set; }


In the following code:

var fromDt = Convert.ToDateTime(this.FromDateAlert.ToShortDateString() + " " + this.FromTimeAlert.ToLongTimeString());


You are converting multiple DateTime values to strings in order to parse them again (this should immediately raise a red flag). When you use the DateTime fields like they were meant to (i.e. containing both Date and TimeOfDay), you can get rid of these redundant conversions:

if (FromAlert > ToAlert)
{
Messages.InfoMessage("FromDate cannot be greater than ToDate", "Alert");
return; //always put this on a separate line!!
}


I have been trying to optimize the filtering process of a Collection based on the DateTime
And why are you parsing the string Alert.Created if you already have a DateTime Alert.GeneratedOn? Just use it:
var filteredAlerts = Alerts.Where(a => a.GeneratedOn >= fromDt && a.GeneratedOn <= toDt);