LINQ

I must admit, I probably overuse LINQ in my code ..it’s just so addictive, the streamlined, compact, pretty, single line of code that offers such robust results.


LINQ started as a simple way to query SQL data through code. In the many years and versions that have been introduced, LINQ has quietly gained abilities and depth ….much like Batman movies (except Ben Affleck ….terrible portrayal, dude).

var query =
 from x in items
 where x.Length > 0
 select x;

It has evolved into a very effective and efficient tool for programmers to utilize while parsing data. It is highly accurate and can be used with any variable type that is enumerable.


Many for loops can be replaced with the simple LINQ statement. There are definitely some loops that can’t be replaced (like your Captain America t-shirt. Timeless) but LINQ can save you some code time and give your processor a break. You are not only helping yourself, but also helping your PC.


Now we have the pleasure of iterating a list, array, or group of some object quickly without having to create a new version of the list.


From this:

var items2 = new List<string>();
foreach (var item in items)
{
If (item.Length > 0)
{
Items2.Add(item);
}
}
Items = items2;
//process items matching conditional

To this:

items = items.Where (x => x.Length > 0).ToList();

I mean, how much more beautiful does it get? It’s simple, straightforward, versatile, and less characters to type. The potential uses are endless.


One of my favorites is looking for a null string in my list of strings. This helps very much when parsing things like orders and shipping values behind the scenes.


orders = orders.Where (x => !String.IsNullOrEmpty (x.Trim ())).ToList ();

It just doesn’t get easier than that.


Let’s say you need to find values in your list that qualify with 2 conditions. Easy.


orderArray = orderArray.Where (x => !String.IsNullOrEmpty (x.Trim ()) && x.Contains("stuff")).ToList (); 


BOOM.


Mic drop.




For a great code resource that includes a lot of useful LINQ examples, check out http://www.albahari.com/nutshell/ where there are pages like:


http://www.albahari.com/nutshell/ch09.aspx that give easy to follow examples and dip into some advanced features.

20 views

Tags: