Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
 Monday, December 17, 2007

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.

 

Monday, December 17, 2007 8:36:31 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET
On this page
Archive
<December 2007>
SunMonTueWedThuFriSat
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Keith Rull
Sign In
Statistics
Total Posts: 254
This Year: 51
This Month: 0
This Week: 0
Comments: 111
Themes
Pick a theme:
Ads
All Content © 2008, Keith Rull
DasBlog theme 'Business' created by Christoph De Baene (delarou)