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)
{
var fromDt = Convert.ToDateTime(this.FromDateAlert.ToShortDateString() + " " + this.FromTimeAlert.ToLongTimeString());
var toDt = Convert.ToDateTime(this.ToDateAlert.ToShortDateString() + " " + this.ToTimeAlert.ToLongTimeString());
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.PagedAlerts = new PagedCollectionView(filteredAlerts);
this.IsBusy = false;
}
Is there a better way of doing this?
1 Answer 1
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());
var toDt = Convert.ToDateTime(this.ToDateAlert.ToShortDateString() + " " + this.ToTimeAlert.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
GeneratedOn property of Alert class.
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);
-
\$\begingroup\$ Hi @codesparkle thanks for your valuable post. For some strange and anonymous reason I had been getting the Alert's CreatedOn prop as a string. So I went up to that guy who was associated with this retrieving Alerts of a system from system center operations manager and asked him why can't you just get CreatedOn as DateTime instead of a string so he changed its type to DateTime. The whole mess of multiple conversions and parsing was 'cause of the CreatedOn prop being a string type. \$\endgroup\$noor syyed– noor syyed2012年08月23日 07:06:15 +00:00Commented Aug 23, 2012 at 7:06
DateTime
s directly. \$\endgroup\$