I have been trying to optimize the filtering process of a Collection 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 to doing this. Your comments would be highly appreciated.
Here is the code snippet with suggested changes.
private DateTime _toDateAlert;
public DateTime ToDateAlert
{
get
{
return this._toDateAlert;
}
set
{
this._toDateAlert = value;
RaisePropertyChanged("ToDateAlert");
}
}
private DateTime _fromDateAlert;
public DateTime FromDateAlert
{
get
{
return this._fromDateAlert;
}
set
{
this._fromDateAlert = value;
RaisePropertyChanged("FromDateAlert");
}
}
public void FilterAlerts()
{
if (this.Alerts != null)
{
if (this.FromDateAlert > this.ToDateAlert)
{
Messages.InfoMessage("FromDate cannot be greater than ToDate", "Alert");
return;
}
this.IsBusy = true;
var filteredAlerts = this.Alerts.Where(a => a.Created >= this.FromDateAlert && a.Created <= ToDateAlert);
this.PagedAlerts = new PagedCollectionView(filteredAlerts);
this.IsBusy = false;
}
}
I have cleaned up all those unnecessary parsing blocks and
FromTimeAlert and ToTimeAlert
ViewModel properties and bound the single
FromDateAlert and ToDateAlert
to both DatePicker and TimePicker controls.
I would be glad to hear from you guys if there is still room for optimisation.
DateTime
s directly. – svick Aug 21 '12 at 17:49