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:

1:privatestatic List<int> TheOld_FilterPositiveItems(List<int> t)

2: {

3: List<int> ret = new List<int>();

4:foreach (int i in t)

5: {

6:if (i > 0)

7: {

8: ret.Add(i);

9: }

10: }

11:return ret;

12: }

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:

1:privatestaticbool intpredicate(int i)

2: {

3:if (i > 0)

4: {

5:returntrue;

6: }

7:returnfalse;

8: }

Pretty simple.

Here is how we use it to filter all the integers:

1:privatestatic List<int> FilterPositiveItems2(List<int> t)

2: {

3: Predicate<int> pred = new Predicate<int>(intpredicate);

4:return t.FindAll(pred);

5: }

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:

@James: Just nitpicking: there is no difference betweeen O(2*N) and O(N). That’s kind of the point of the big-O-Notation. Anyway, I think appending an item to a List is O(N), so the “good old foreach”-version might actually be O(N^2).

I usually use Enumerable.Where, which is equivalent to your version. I guess the most efficient way would be to filter the items inline (the way std::remove_if in the C++ STL works).

The third way (the slick) isn’t anything new to .NET. It has been there since delegates and generics were introduced. Just replace the lambda expression with an inline anonymous method and it’s the same thing. Granted, it’s not as pretty.