The Daily Parker

Politics, Weather, Photography, and the Dog

L is for LINQ

Blogging A to ZDay 12 of the Blogging A-to-Z challenge will introduce you to LINQ, another way .NET makes your life easier.

LINQ stands for Language INtegrated Query, which Microsoft describes as follows:

Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. With LINQ, a query is a first-class language construct, just like classes, methods, events.

LINQ does a lot of things, so let me show just a small example. Before LINQ, if you wanted to loop through a collection and filter for specific characteristics, you'd have to do something like this:

public static ICollection<Room> ForEachLooping(IEnumerable<Room> rooms, string filter)
{
	var result = new List<Room>();
	foreach (var item in rooms)
	{
		if (filter == item.Name) result.Add(item);
	}

	return result;
}

Here's the LINQ version; see if you can spot the difference:

public static ICollection<Room> LinqLooping(IEnumerable<Room> rooms, string filter)
{
	return rooms.Where(p => p.Name == filter).ToList();
}

LINQ adds a whole set of extension methods to the IEnumerable<T> interface, including Average, Sum, Sort, Join...basically, everything you can do with a SQL statement, you can do with a LINQ statement.

In fact, there's an alternate syntax that's even more SQL-like:

public static ICollection<Room> SqlishLinq(IEnumerable<Room> rooms, string filter)
{
	return
		(from r in rooms
		where r.Name == filter
		select r)
	.ToList();
}

Note that LINQ naturally operates on and returns IEnumerable<T>, not ICollection<T>, so I invoked the .ToList() method for easier testing. In fact you would want to return IEnumerable<T> so that you can easily chain methods that use LINQ, as LINQ doesn't evaluate the whole query chain until you try to use one of its results. Calling ToList() forces an invocation.

LINQ is super-powerful and super-handy in too many cases to enumerate* in this short post. But if you use ReSharper (see Tuesday's post), you will learn it super-quickly.

(* See what I did there?)

Comments are closed