All posts tagged 'INQ'

.NET Musings

An Intro to LINQ to Objects in VS2008 and C#

Technorati Tags: ,,,

In my post explaining Anonymous Types, the build up was all about Language INtegrated Query, or LINQ.  There are several flavors of LINQ (LINQ to SQL, LINQ to NHibernate, LINQ to XML, etc).  What this post will focus on is LINQ to objects, which in my opinion is the best and should be to the widest used flavor.

Before LINQ, if you wanted to build a sub-set of a list, you would enumerate through that list, adding the correct items into a new list, that would then be returned.

IList<Product> products = new ProductRepository().GetAll();
var matches = new List<Product>();
foreach (var p in products)
{
  if (p.UnitCost >= 100)
  {
    matches.Add(p);
  }
}
return matches;

If you wanted to transform the results into other objects (e.g. something more streamlined that doesn’t contain all of the data of the original class), then you would have significantly more work to do.


The LINQ assemblies and namespaces introduce a query language that we can use against strongly types lists of objects.  The language itself (if you are used to SQL) takes a bit of getting used to.  Instead of:


SELECT {blah} FROM {blah} WHERE {blah} ORDER BY {blah}


the FROM comes first.  The reason for this is so the compiler knows the type that we are working with.  The return type of the LINQ expression is an IEnumerable<>.  To replicate the function above, we write the following code:

IList<Product> products = new ProductRepository().GetAll();
IEnumerable<Product> matches = 
   from product in _products
   where product.UnitCost >= 100
   select product;
return matches.ToList();

If you only want to return a subset of the product properties (this is referred as Projecting new data types), what changes is the “select” part of the LINQ expression. Instead of “select product” we could write:

IList<Product> products = new ProductRepository().GetAll();
var matches = from product in products
    where product.UnitCost >= 100
    select new {product.ID, product.UnitCost};
foreach (var itm in matches)
{
  Console.WriteLine("{0}:{1}", itm.ID, itm.UnitCost);
}

This is just a quick intro into LINQ to Objects.  There is so much more to it, and we will continue to dive deeper in future posts.


Happy Coding!

Managed Windows Shared Hosting by OrcsWeb