Thursday, September 13, 2012

LINQ Extension Methods Cheat Sheet

LINQ Extension Methods are great. Here's a cheat sheet of the common ones:


Filter

Takes a larger set down to a smaller set

First
  • customers.First(c => c.LastName == "Anderson")
    The first customer with a last name of Anderson
Last
  • customers.Last(c => c.LastName == "Anderson")
    The last customer with a last name of Anderson
Single
  • customers.Single(c => c.Id == 456)
    The only customer with an ID of 456
Where
  • customers.Where(c => c.Active == true)
    All customers that are Active
FirstOrDefault
  • customers.FirstOrDefault(c => c.LastName == "Anderson")
    The first customer with a last name of Anderson or null if there isn't one
LastOrDefault
  • customers.LastOrDefault(c => c.LastName == "Anderson")
    The last customer with a last name of Anderson or null if there isn't one
SingleOrDefault
  • customers.SingleOrDefault(c => c.Id = 999)
    The only customer with an ID of 999 or null if there isn't one

Sort

Returns a copy of a set but in a different order

OrderBy
  • customers.OrderBy(c => c.LastName)
    Returns the customers sorted alphabetically by last name
OrderByDescending
  • customers.OrderByDescending(c => c.LastOrderDate)
    Returns the customers sorted by the date they last placed an order (most recent first)
ThenBy (must be done after OrderBy or OrderByDescending)
  • customers.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)
    Returns the customers sorted first by last name then by first name
ThenByDescending (must be done after OrderBy or OrderByDescending)
  • customers.Order(c => c.Category).ThenByDescending(c => c.LastOrderDate)
    Returns the customers sorted first by category then by the date they last placed an order (most recent first)

Conditional

Answers a yes/no question based on a set

All
  • customers.All(c => c.Active == true)
    Is every customer in the set active?
Any
  • customers.Any(c => c.LastOrderDate > DateTime.Now.AddDays(-7))
    Did any customer in the set make an order in the past 7 days?

Projection

Transforms a set of objects in one form to a set of objects in another form

Select
  • IEnumerable<string> names = customers.Select(c => c.FirstName)
    Select the first name of every customer (transform each Customer object to a string object)

Extension methods always return a COPY:

  • IEnumerable<Customer> sorted = customers.OrderBy(c => c.LastName)

No comments:

Post a Comment