fuzzelogic Solutions

March 14, 2009

Find….

Filed under: Programming, c# — Tags: , , , , , — admin @ 1:57 am
In 2.0 when you’re looking for an item within a List<T> object you can do the following…
Lets assume you’re looking for an Task item with a known Id.
[sourcecode language='csharp']
int id = int.Parse(taskList.SelectedValue);
foreach (Task t in AllTasks)
{
    if (t.Id == id)
        return t;
}
[/sourcecode ]
You loop through all the items in the collection and return the first one that matches.
 

 

But in 2.0 you can replace that with the Find method on the List<T> object and smacking in an anonymous/inline delegate ….

 
So the above now becomes.
 
int id = int.Parse(taskList.SelectedValue);
return AllTasks.Find(delegate(Task t) { return t.Id == id; });
 
the Find method takes a single argument which is a predicate delegate and searches through the list for the condition defined by the predicate and returns the first one found.
 
 
..And in 3.5 .. it gets even simpler (in my opinion): 
int id = int.Parse(taskList.SelectedValue);
return AllTasks.Find(x=>x.id==id);
 
Hope this helps!
Thanx

Powered by WordPress