Filtering
Whilst you can still use SQL Queries against your Database to perform searches, you can also perform searches against your collections. This is achieved by running you Collection through a filter. It’s easy to set up a Filter Class as s -
public class FilterFoos
{
private double _PriceFrom = -1;
public double PriceFrom
{
set
{
_PriceFrom = value;
}
get
{
return _PriceFrom;
}
}
private FooCollection _Foos;
public FooCollection Foos
{
set
{
_Foos = value;
}
}
public FooCollection Filter()
{
FooCollection Results = _Foos;
//If we have a Minimum Price let's filter the Foos by that
if (_PriceFrom > 0)
{
FooCollection G = new FooCollection();
foreach(Foo C in Results)
{
if(C.Price >= _PriceFrom)
{
G.Add(C);
}
}
Results = G;
}
return Results;
}
}
The above only has one ”Filter” inside it, but it’s really simple to set up more filters, and the above can be very easily used with your Strongly Typed Objects: -
private FooCollection DoFilter(FooCollection CC)
{
FilterFoos F = new FilterFoos();
if (Request.Form["PriceFrom"] != null)
{
F.PriceFrom = Convert.ToDouble(Request.Form["PriceFrom"].ToString());
}
//Perform the Filter on Price From
F.Foos = CC;
CC = F.Filter();
return CC;
}
The simplest way of having your Collections sorted is by running the “Order By” clause in your SQL Lookup, and then passing the Rows in to your collection, however you may have in memory collections, and to perform sorting on these you will need to use objects called comparers and the ICompare interface, with a sprinkle of Array.Sort().
A Comparer Class needs to be created for the Properties of your objects that you wish to sort on as follows: -
public class FooTitleComparer : IComparer
{
public int Compare(object x, object y)
{
Foo xFoo = ((Foo)x);
Foo yFoo = ((Foo)y);
return String.Compare(xFoo.Title,yFoo.Title);
}
public FooTitleComparer()
{
}
}
Then in the Collection a Sort method needs to be created: -
public void Sort(string SortProperty)
{
if (SortProperty.ToLower() == "title")
{
FooTitleComparer myFooTitleComparer = new FooTitleComparer();
this.InnerList.Sort(myFooTitleComparer);
}
}
Usage of the Sort method in your code is very simple to -
C.Sort("Title");
public void Sort(string SortProperty)
{
if (SortProperty.ToLower() == "title")
{
FooTitleComparer myFooTitleComparer = new FooTitleComparer();
this.InnerList.Sort(myFooTitleComparer);
}
}
Whilst the above is very flexible it does not allow us to sort in multiple directions (Ascending and Descending). To achieve this functionality more work has to be done with the Comparer Classes. An article covering this can be found here: -
http://www.c-sharpcorner.com/Code/2002/June/CollectionObgOrdering.asp