Getting Started With LINQ

I mentioned Linq to SQL in a previous post and from that post it probably sounded like I wasn't a fan. For creating business objects I'm not sure if Linq to SQL is a great solution. Linq to SQL isn't very flexible when it comes to configuring your mapping. Plus there's the general uneasiness I've been feeling with ORMs lately.

When it comes to LINQ on the other hand, I'm a huge fan. I've been working on a couple of things that are written using .NET 3.5 and the times that I've gotten to use LINQ I've come away really impressed. So far I've had the opportunity to use Linq to SQL, Linq to XML and Linq to Objects and all of them are great technologies in my opinion.

LINQ to XML makes reading simple XML documents completely trivial. I was going to post an example of how you could read in a collection of objects, and even populate collections on those objects using a sub-query using only a few lines of code, but then I realized there's no sense doing something Scott Guthrie already did much better than I could.

LINQ to Objects is big too. LINQ to Objects doesn't do anything that you couldn't do by writing your own loop, but it allows you to do things in a much more concise and more importantly, readable manner.

Let's say I have a collection of Account objects representing bank accounts and I need to print out a list of reports that are older than a year and report some statistics on those accounts and sort the list:

decimal averageBalance = 0;
decimal averageTransactions = 0;
List<Account> oldAccounts = new List<Account>();

foreach (Account account in accounts)
{
    if (account.AccountOpened < DateTime.Today.AddYears(-1))
    {
        averageBalance += account.Balance;
        averageTransactions += account.Transactions.Count;
        oldAccounts.Add(account);
    }
}

averageBalance = averageBalance / oldAccounts.Count;
averageTransactions = averageTransactions / oldAccounts.Count;

Comparison<Account> sortMethod = delegate(Account a1, Account a2)
	{ return string.Compare(a1.Name, a2.Name); };
oldAccounts.Sort(sortMethod);

 

Or we could do the same thing with LINQ:

var oldAccounts = from account in accounts
                  where account.AccountOpened < DateTime.Today.AddYears(-1)
                  orderby account.Name
                  select account;

decimal averageBalance = oldAccounts.Average(a => a.Balance);
decimal averageTransactions = oldAccounts.Average(a => (decimal)a.Transactions.Count);

Which of those two blocks of code would you rather write or have to maintain? The LINQ version saves several lines, but more importantly, it's much more readable. The easier code is to read the faster someone modifying the code can understand it and be ready to make improvements. To me this is the real value of LINQ. It's ability to create extremely readable and flexible queries.

I think it's going to be important for every .NET developer who wants to stay on top of their game to have a solid understanding of LINQ, extension methods and predicates going forward. These concepts are very different from what the average C# developer is used to but they can really improve the way they work, so any developer who can incorporate the new technologies in .NET 3.5 into the way they way they think about code is going to be at a big advantage.

Print | posted on Tuesday, February 26, 2008 8:22 PM

Comments on this post

# re: Getting Started With LINQ

Requesting Gravatar...
I agree, LINQ is freaking awesome. Maybe you could do a post on the JOIN query. Would be cool to see something a little more advanced like that.
Left by Captain Barnicle on Feb 28, 2008 6:21 PM

# re: Getting Started With LINQ

Requesting Gravatar...
thank you
Left by sam on Dec 14, 2009 4:39 AM

Your comment:

 (will show your gravatar)
 
Please add 4 and 8 and type the answer here: