Over a million developers have joined DZone.

Filtering List Items, The Old, The New and the Slick

DZone's Guide to

Filtering List Items, The Old, The New and the Slick

· ·
Free Resource

Hi 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)
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.




Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}