65.9K
CodeProject is changing. Read more.
Home

using of lambda expression and removing foreach/for loop

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.27/5 (10 votes)

May 10, 2011

CPOL
viewsIcon

23700

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
public Contact GetContact(int Id)
{
        //return (from c in _entities.Contacts //LINQ
        //        where c.Id == Id
        //        select c).FirstOrDefault();
        return _entities.Contacts.FirstOrDefault(m => m.Id == Id); //Lamda
}
Obviously lambda expression will make life easier. We can use find function and many more using lambda expression...