Blog Subscribe to our blog Subscribe to our RSS blog feed Bookmark and Share

More Blog Entries

LINQ to Objects

As I promised in my last post, I’ll be covering the different LINQ technologies. This post will talk about using LINQ to query in-memory collections.  We’ll touch lightly on the concept of lambda expressions, but there will be more about those in a future article.

How many times have we written a ‘foreach’ statement to iterate through a collection looking for a value?  Or wished that we could sort a collection?  Or do some set-oriented operations, like unions, intersections, or maybe even a SQL-like ‘Select’?  LINQ does all of these.

Compliments of something called ‘extension methods’, all collections on DotNet 3.5 have a full set of LINQ methods available.  Create a simple array of ints, and that array has all the power of LINQ.
Here are a few examples of what you can do.

Assume an integer array:

int[] myInts = { 1, 5, 3, 4 };


In the past, if we wanted to find out if myInts contains the number 7, we’d need to foreach through the collection.  Now, we simply write:


bool containsSeven = myInts.Contains(7);


What could be easier?  If we wanted to print a sorted list of the integers, we can now write:

foreach (int i in myInts.OrderBy(n => n))


The “n => n” is a lambda expression.  One way to read them is, “If you give me what’s on the left of the arrow, I’ll give you back what’s on the right side of the arrow.”  In this case, if we provide ‘n’ to the ordering method, it will return (and use) ‘n’.  This is a very simple use of a lambda expression; we’ll talk more about these in an upcoming article.


To get an idea of the kinds of methods available to you, use Visual Studio’s IntelliSense feature.  Simply type a dot after a collection’s variable name, and look at the methods that you can call.

We get so used to using LINQ to query SQL that we often forget about the power of LINQ applied to in-memory collections.  Keep the technique in mind--you’ll be amazed at how often you can use it.

- Ben Furino, .NET Programming Manager

Tags: tech LINQ 

Leave a Comment