I've been banging .NET 3.5 lately and this rendezvouz with LINQ (Language Integrated Query) has been making my brain smile alot. I mean, how can you not like something so easy and well defined and makes your life as developer alot easier.
Anyhow, I just wanted to post my LINQ cheat sheet. It's not much and it's not even complete yet (I call this part 1.1). It consist of a few snippets that you might commonly do when doing LINQ processing. I'm planning to update this and hopefully I could find time this week to add some more piece of code that would demonstrate the other LINQ topics that I missed.
Anyway, here's some LINQ snippets:
//create our PersonService object
PersonService ps = new PersonService();
//get the list of person
PersonList listOfPerson = ps.GetPersonList();
//get a list of people with Gender set to Male
var maleOnlyList =
from l
in listOfPerson
where l.Gender == Gender.Male
select l;
//get a list of people with Gender set to female
//and declaring the returned fields
var femaleOnlyList =
from l
in listOfPerson
where l.Gender == Gender.Female
select new {
l.PersonID,
l.FirstName,
l.MiddleName,
l.LastName,
l.Email,
l.BirthDate,
l.Gender,
l.DateCreated };
//specify age
int selectedAge = 25;
//get a list of people with age greater than 25
var ageIsGreaterThan25 =
from l
in listOfPerson
where l.BirthDate >= DateTime.Now.AddYears(-selectedAge)
select l;
//get a list of people with a birthdate between a specified range
var birthdateBetweenRange =
from l
in listOfPerson
where
l.BirthDate >= DateTime.Parse("1/1/1980")
&& l.BirthDate <= DateTime.Parse("1/1/1981")
select l;
//order the result by lastname
var orderByLastNameSimple =
from l
in listOfPerson
orderby l.LastName
select l;
//order the list by birthdate and lastname
var orderByMultiple =
from l
in listOfPerson
orderby l.BirthDate descending, l.LastName ascending
select l;
//take three records
var takeThree = listOfPerson.Take(3);
//go to the 10th record and then take 3 records from there
var skipTenTakeThree = listOfPerson.Skip(10).Take(3);
//skip up until the Lastname is not equal to Thornton
var skipWhile = listOfPerson.SkipWhile(n => n.LastName != "Thornton");
P.S: There's more LINQ examples at the MSDN website.