Joins Using LINQ Query Expressions in .NET 3.5
(
Aug 21 2007 - 07:50:33 PM by
Timothy Khouri) - [
print blog
post]
The more I use Visual Studio 2008 (and in particular, the new language features of .NET 3.5), the more I wonder how I ever programmed without it. My current love is the "Language Integrated Query" (LINQ) features that have been introduced in .NET 3.5 (with LINQ to SQL, XML, Entities etc). What I'm talking about right now is just the language itself (as the below example would just be considered LINQ to Objects).
If you're used to using SQL, then you're probably familiar with the "joining" (linking multiple sources together in your "from clause"). You've probably thought before, "this functionality would be great in every day programming, not just in SQL". Here is a quick snippet of C# code that shows how to perform joining using LINQ. This is just straight query expressions here, nothing special.
var result = from article in this.Articles
join author in this.Authors
on article.Author equals author.Name
select new
{
ArticleTitle = article.Title,
ArticleBody = article.Body,
AuthorName = author.Name,
AuthorDateOfBirth = author.DateOfBirth
};
Those two objects (this.Articles and this.Authors) are simply generic lists of a couple of objects I've created. If you'd like to see the whole thing to get more insight on how easy it is to join in LINQ, here's the code:
public class Article
{
public string Title { get; set; }
public string Body { get; set; }
public string Author { get; set; }
}
private class Author
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
private List<Article> Articles = new List<Article>();
private List<Author> Authors = new List<Author>();