Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple MVC NerdDinners Lambda

In this code from Microsoft's MVC Tutorial NerdDinners:

public class DinnerRepository {

private NerdDinnerDataContext db = new NerdDinnerDataContext();

//
// Query Methods

public IQueryable<Dinner> FindAllDinners() {
    return db.Dinners;
}

public IQueryable<Dinner> FindUpcomingDinners() {
    return from dinner in db.Dinners
           where dinner.EventDate > DateTime.Now
           orderby dinner.EventDate
           select dinner;
}

public Dinner GetDinner(int id) {
    return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}

//
// Insert/Delete Methods

public void Add(Dinner dinner) {
    db.Dinners.InsertOnSubmit(dinner);
}

public void Delete(Dinner dinner) {
    db.RSVPs.DeleteAllOnSubmit(dinner.RSVPs);
    db.Dinners.DeleteOnSubmit(dinner);
}

//
// Persistence 

public void Save() {
    db.SubmitChanges();
} 

}

What does:

public Dinner GetDinner(int id) {
    return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}

the "d" mean? How does this code work? I know it it bringing back dinners where dinnerid matches id from the function parameter. I don't understand the "d goes to..." means. I know it is a lambda but I don't really get it. What is the "d" for? What does it do?

Could this have been written without the lambda here (how)?

like image 432
johnny Avatar asked Jan 23 '23 15:01

johnny


2 Answers

You should probably read up on anonymous methods.

Basically the code you are referring to can be written as an anonymous method without lamba syntax like this:

public Dinner GetDinner(int id) {    
   return db.Dinners.SingleOrDefault(delegate (Dinner d) {
                                       return d.DinnerID == id;
                                     });
}
like image 187
Jimmie R. Houts Avatar answered Jan 30 '23 23:01

Jimmie R. Houts


This is similar too...

from d in db.Dinners
where d.DinnerID == id
select d

The code basically loops around the dinners returning the first Dinner or the default if none is found.

This is a case where the naming conventions used in a sample aren't always appropriate in production. Using a "d" as a local variable is usually fround upon and choosing a variable name of "dinner" would probably be more appropriate, although in this case the scope of d is so small it is clear either way, as long as you know how lambda expressions work.

like image 41
David McEwing Avatar answered Jan 30 '23 21:01

David McEwing