Tips in C#
This page is a reminder and how-to for my best tips in C#
How to find items inside a generic list<T>
In C# language we can extract objects form a list in various ways.
The methods listed below are efficient, but the readability is different from one
to each others.
Every example uses the namespace System.Collections.Generic.
Moreover the list that we'll inspect with our search will be List<Person>
which is a list of the simple class Person that has only two public fields: string
Name, int Age.
The code task is to retrieve all persons that are less than 30 years old.
1) The classical way: foreach
List<Person> personUnder30 = new List<Person>();
foreach (Person p in listPerson)
{
if (p.Age < 30) personUnder30.Add(p);
}
|
With this methods we have to manually cycle inside our list. The task of retrieving
every person whose age is less than 30, is very simple and the readability is however
great.
In a real world application the enumeration of lists through foreach clause, could
be less simple and clear in particularly if our objects structure is recursive or
much deep than our one-level-person.
2) The FindAll() method.
List<Person> personUnder30 =
listPerson.FindAll(delegate(Person p){ return p.Age < 30;});
|
It's a more elegant method who allows to retrieve the result sublist with one instruction.
The FindAll method (as many other methods of generic lists) expects, as a parameter,
a System.Predicate delegate.
Predicate are one of the pre-packaged delegates that .NET 2.0 offers to manage generics.
This one in particular expects a type as parameter and return a boolean value.
In our example we pass as parameter the type Person so the enumeration could extract
from listPerson the right type.
In the body of the anonymous method we can pass code that could interact with every
instance of Person enumerated from the list. Our code has to evaluate the instance
and has to return true if the instance of person respects our filter criteria otherwise
false.
Predicate is a delegate used with various methods of generic lists such as Find,
FindAll, Exists, FindLast, RemoveAll...
3) The Linq method.
var personUnder30 =
from p in listPerson
where p.Age < 30
select p;
|
Linq is available from 3.5 release of .NET Framework and requires for namespace
System.Linq. This new syntax is very similar to SQL and allows to extract our sublist
inside a var object.
The query result personUnder30 is stored into a var that is a special variable with
a limited scope (exists only inside the method) and type safety guarantee from the
select instruction (select return p which is of type Person so var will be a list
of Person).
In our case the select instruction doesn't return an anonymous type so we can avoid
the use of var and increment readability of our code.
IEnumerable<Person> personUnder30 =
from p in listPerson
where p.Age < 30
select p;
|