Day 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);
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)
(from r in rooms
where r.Name == filter
Note that LINQ naturally operates on and returns
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?)