Home > Blogs > LINQ: I'm a believer

LINQ: I'm a believer

By  Feb 7, 2008

Topics: Programming, Windows Programming

Language-integrated query (LINQ) is a new technology introduced with .NET 3.5.  The C# 3.0 language has been extended to support it.  LINQ is, in essence, a query language for in-memory data.  Think of SQL for your data structures and you get the idea.

Sometimes you have to see a thing in action before you understand just how powerful it is.  The other day I had the opportunity to learn that about LINQ.

Suppose you have a Dictionary of inventory items. For example:
class InventoryItem
{
    public string StockNumber {get; private set; }
    public int Count { get; set; }
    public int ReorderThreshold { get; set; }
    // other fields here
}
Dictionary<string,InventoryItem> inventory =
    new Dictionary<string, InventoryItem>();

Now, imagine you want to want to go through the list and select all the items whose Count is less than the ReorderThreshold, and output the list sorted in StockNumber order. The traditional way to do this is to go through the Dictionary one item at a time (using foreach) and create a List of items. Then, sort the list and output. Like this:
// Select items to reorder
List<InventoryItem> reorderList = new List<InventoryItem>();
foreach (var kvp in inventory)
{
    if (kvp.Value.Count <= kvp.Value.ReorderThreshold)
      reorderList.Add(kvp.Value);
}

// sort the list by stock number
reorderList.Sort(delegate(InventoryItem i1, InventoryItem i2)
{
  return i1.StockNumber.CompareTo(i2.StockNumber);
});

// Now output all the items
foreach (var item in reorderList)
{
  OutputItem(item);
}
All that goes away with LINQ. The new way to do things is build a query and let the runtime deal with selection and sorting:

var reorderList =
    from item in inventory
    where item.Count <= item.ReorderThreshold
    orderby item.StockNumber
    select item;

foreach (var item in reorderList)
{
  OutputItem(item);
}
Sure, I understand that I'm not saving any execution time. It's even possible that the runtime generated code for selecting and sorting is less optimal than what I could write myself. But most of the time I don't care. In a majority of cases, I won't even notice a few milliseconds or even seconds in something like this. And it makes the code much easier to write.

I'm definitely a convert. LINQ is cool.


Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed