Filtering List Items, The Old, The New and the Slick
Join the DZone community and get the full member experience.
Join For FreeHi all
I was into filtering items lately and I have decided to write about some of the techniques out there starting with the old:
The good old Foreach
Well we have all used this before once you get a list in your hands just iterate through all the items and select the ones you want:
private static List<int> TheOld_FilterPositiveItems(List<int> t)
{
List<int> ret = new List<int>();
foreach (int i in t)
{
if (i > 0)
{
ret.Add(i);
}
}
return ret;
}
I hope you are not using this method. As there are other good methods like this one:
Filtering Using Predicates
This method is much more simple and nice. first we will have to define a predicate that will point to a function that will hold the logic of the filtering. Here is the function that will provide the testing of whether the integer is positive or not:
private static bool intpredicate(int i)
{
if (i > 0)
{
return true;
}
return false;
}
Pretty simple.
Here is how we use it to filter all the integers:
private static List<int> FilterPositiveItems2(List<int> t)
{
Predicate<int> pred = new Predicate<int>(intpredicate);
return t.FindAll(pred);
}
That takes care of filtering using predicates. Not a bad way of doing it but here comes the slickest way of filtering:
Filtering Using Lmbda Expressions
This is just an improvement on the previous method instead of using the predicate we will provide List.FindAll with a lambda expression.
We will use the following expression:
n => n>0 which can be translated like this: n where n is larger then 0.
this lambda expression has a return type of boolean so it can be placed instead of the predicate:
private static List<int> TheSlick_FilterPositiveItems(List<int> t)
{
return t.FindAll(n => n > 0);
}
That’s it.
Enjoy
Amit
Published at DZone with permission of Amit Raz. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments