Find a specific value within a generic list with a Lambda Expression using C#

With the release of C# 3.0 came Lambda Expressions. In a previous post I searched a generic list using a delegate, this is because, perhaps, I have done so much programming with C# 2.0 that it’s just a habit now. Time to move onto better, newer things, like Lambda Expressions.

In the previous example I used these 2 lines of code to search for a specific value within a generic list. One list, contains a list of a class and the other is a list of strings.

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
Currency result = 
       FindItClass.Find(delegate(Currency cur) 
            { return cur.Code == searchFor; });
 
string stringResult =
       FindIt.Find(delegate(string str) 
            { return str == searchFor; });
[/sourcecode]

To achieve the same thing using a Lambda Expression is shown below.

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
Currency result = FindItClass.Find(r => r.Code == searchFor);
string stringResult = FindIt.Find(r => r == searchFor);
[/sourcecode]

Using a Lambda Expression in this example requires less code. Since the results are the same, it is always good practice to write as little code as required to meet the objectives.

Download the source.




Leave a Comment

Your email address will not be published.