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 objectPersonService ps = new PersonService();//get the list of personPersonList listOfPerson = ps.GetPersonList();//get a list of people with Gender set to Malevar maleOnlyList =from lin listOfPersonwhere l.Gender == Gender.Maleselect l;//get a list of people with Gender set to female//and declaring the returned fieldsvar femaleOnlyList =from lin listOfPersonwhere l.Gender == Gender.Femaleselect new { l.PersonID, l.FirstName, l.MiddleName, l.LastName, l.Email, l.BirthDate, l.Gender, l.DateCreated };//specify ageint selectedAge = 25;//get a list of people with age greater than 25var ageIsGreaterThan25 =from lin listOfPersonwhere l.BirthDate >= DateTime.Now.AddYears(-selectedAge)select l;//get a list of people with a birthdate between a specified rangevar birthdateBetweenRange =from lin listOfPersonwhere l.BirthDate >= DateTime.Parse("1/1/1980") && l.BirthDate <= DateTime.Parse("1/1/1981")select l;//order the result by lastnamevar orderByLastNameSimple =from lin listOfPersonorderby l.LastNameselect l;//order the list by birthdate and lastnamevar orderByMultiple =from lin listOfPersonorderby l.BirthDate descending, l.LastName ascendingselect l;//take three recordsvar takeThree = listOfPerson.Take(3);//go to the 10th record and then take 3 records from therevar skipTenTakeThree = listOfPerson.Skip(10).Take(3);//skip up until the Lastname is not equal to Thorntonvar skipWhile = listOfPerson.SkipWhile(n => n.LastName != "Thornton");
P.S: There's more LINQ examples at the MSDN website.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.