| |
|
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 becuase, 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. |
| |
Currency result =
FindItClass.Find(delegate(Currency cur)
{ return cur.Code == searchFor; });
string stringResult =
FindIt.Find(delegate(string str)
{ return str == searchFor; });
|
| |
| To achieve the same thing using a Lambda Expression is shown below. |
| |
Currency result = FindItClass.Find(r => r.Code == searchFor);
string stringResult = FindIt.Find(r => r == searchFor);
|
| |
| Using a Lambda Expression in this example requires less code. Since the
results are the same, it is always cood practice to write as little code as required to
meet the objectives. |
| |
| Download the source |
|
|
| |
|
|
| |
|
|
| |
| |
| Posts: 113 |
| Comments:
86 |
| Fundamentals:
16 |
| |
 |
| |
| |
|
| |
 |
| |
 |
| |
 |
| |
|
| 2011 December (2) |
| 2011 November (6) |
| 2011 October (7) |
| 2011 September (7) |
| 2011 August (9) |
| 2011 July (9) |
| 2011 June (8) |
| 2011 May (9) |
| 2011 April (7) |
| 2011 March (9) |
| 2011 February (8) |
| 2011 January (8) |
| 2010 December (7) |
| 2010 November (8) |
| 2010 October (4) |
| |
| |
|
| |
|
|
| |
| |
|
The sample code on this website is provided to illustrate a concept and should not be used in
applications or Web sites without proper professional consultation, as it may not illustrate
the safest coding practices. I assume no liability for incidental or consequential damages
should the sample code be used for purposes other than as intended.
|
| |
|
| | | |