Click here to Skip to main content
13,291,084 members (58,073 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


3 bookmarked
Posted 10 May 2011

using of lambda expression and removing foreach/for loop

, 10 May 2011
Rate this:
Please Sign up or sign in to vote.
lambda expression
I want to show a simple use of Lamda expression in our C# code which remove tedious lines of code,
_entities is a object of Database which has a list of Contact is Contacts I am going to search a contact by a Id which is used as parameter in a function we can find the contact by three way

1. By using foreach/for loop and inside loop we can check if current contact has same id as parameter
2. using LINQ which is written over here as commented.
3. Using LAMDA Exp. which is also written I am going to use in future

<pre lang="c#">public Contact GetContact(int Id)<br />
{<br />
        //return (from c in _entities.Contacts //LINQ<br />
        //        where c.Id == Id<br />
        //        select c).FirstOrDefault();<br />
        return _entities.Contacts.FirstOrDefault(m => m.Id == Id); //Lamda<br />
}</pre><br />

Obviously lambda expression will make life easier. We can use find function and many more using lambda expression...


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Kishore Barik
Software Developer (Senior) Insync Tech-Fin Solutions Ltd.
India India
This member doesn't quite have enough reputation to be able to display their biography and homepage.

You may also be interested in...


Comments and Discussions

GeneralIf you were to compare all 4 (for,foreach,LINQ,Lambda) with ... Pin
nbgangsta10-May-11 23:12
membernbgangsta10-May-11 23:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171207.1 | Last Updated 10 May 2011
Article Copyright 2011 by Kishore Barik
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid