SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast drownedbeaver's Avatar
    Join Date
    Aug 2011
    Location
    Philippines
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Confusion on TUTORIALS IN MVC1

    I have an e-book THE MVC1 Quickly....
    There is a part there
    Code:
    public ActionResult UpdateContact()
    {
    int id = 0;
    if (int.TryParse(Request.Form["Id"], out id))
    {
    Contact contact = Contacts.Single(c => c.Id == id);
    contact.Name = Request.Form["Name"];
    contact.Email = Request.Form["Email"];
    }
    return RedirectToAction("Index");
    }
    What does c for? Its not even declared?

  2. #2
    Chopped Liver bronze trophy imaginekitty's Avatar
    Join Date
    Aug 2007
    Location
    Pennsyltucky
    Posts
    1,494
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    It's Linq. .Single chooses one record from the collection and throws an exception if more than one record exists to meet the select. c is defined in the delegate. It selects the record where the collection's Id is equal to id from the form.

  3. #3
    Resident OCD goofball! bronze trophy Serenarules's Avatar
    Join Date
    Dec 2002
    Posts
    1,911
    Mentioned
    26 Post(s)
    Tagged
    0 Thread(s)
    Delegates are confusing to those new to them. So let me step it out...

    The line "Contacts.Single(c => c.Id == id)" should simple be read like this:

    From Contacts I want a Single contact, which we shall call c, where c.Id is equivalent to id.

    c is merely a placeholder. The (c => ?) part just says, look at each element in the set and if it meets condition ? then return it. Personally, I don't like using single letters like that. The following is more clear.

    var desiredContact = Contacts.Single(contact => contact.Username == "foobar");
    // grab the one contact from the set where username is foobar.

    Note: if record does not exist, the Single method will throw an exception. If you don't want to handle them, use SingleOrDefault instead.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •