Post

# LINQ Operators in Action: Part 1

Trying to catch up with your New Year's resolution is indeed tough! One of my resolutions for 2015 was to at least write a minimum of one article each month. Oops, better catch up, so here is my article, obviously a day late!

Since LINQ was introduced, many developers have used it and I believe a few old-school somethings might be contemplating to use it soon, right? Whether you have used LINQ with your programming projects or not, this series of articles should help you re-factor some of the old ways of programming with some funky LINQ alternatives.

Language-Integrated Query (LINQ)

Simply put, Language-Integrated Query (LINQ) allows us to write queries directly in our code. Those queries can do various actions on relational databases, XML, in-memory container objects, such as arrays and lists. If you want more information then check out the following MSDN library link.

I'm not going into each and every detail of LINQ, instead I'm going to focus on presenting how various LINQ operators can help us write simple and better code. Can I survive without LINQ? Sure, yes, we have and we will continue to. However, why not adopt a newer approach and make our lives easier! Trust me, if you have not used it, you will become addicted once you start to see the power that LINQ brings into our day-to-day coding.

One of the ways I learned about using LINQ was to refactor some of my old code and see how LINQ can help me. I'll take a similar approach here and let's start with sample code and refactor it with a LINQ query. I promise, once you understand the power of all LINQ operators, you will see plenty of refactoring opportunities in your code.

Let's get started. So, what is the following code doing?

1. int[] numbers = {2,3,5,8,12,29};
2. bool isGreater = false;
3. for(int i=0;i<numbers.Length;i++)
4. {
5.    if(numbers[i]>10)
6.    {
7.       isGreater = true;
8.       break;
9.    }
10. }
You got it, it is a simple “for” loop and it is stepping through an array of integers and trying to determine whether a number in the array is greater than 10. If found then it will set the boolean varaible “isGreater” to true. If I ask you, can we simplify this code further? I am sure the answer will be a resounding yes, we can use “foreach”. I'll still persist, how about even simpler, just in one line? Now, here comes the power of LINQ and its operators. So, here is the first LINQ operator.

Any Operator

The Any operator returns true if there is at least a single element in an array that matches a given condition. Here is our loop refactored after using Any:
1. int[] numbers = {2,3,5,8,12,29};
2. bool isGreater = numbers.Any (n => n > 10);
Honestly, do you think it is no better than our “for” loop example? Yes, I agree with you, it is. Like our “for” loop, the “Any” operator goes through the “numbers” array and as soon it finds the condition has been met it returns with a “true” boolean result.

In a real-world example, imagine that your CRM application has the collection SalesPersons and you can use the “Any” operator to go through the collection and determine the top performing individuals based on the Sales figure against any given threshold.

All Operator

The All operators, as the name suggests, is used when we want to determine whether all elements in any given collection matches a given condition. Once again, let's see how to do this using a traditional “for” loop and compare it with the refactored version using the “All” LINQ operator.
1. int[] numbers = {2,3,5,8,12,29};
2. bool isAll = true;
3. for(int i=0;i<numbers.Length;i++)
4. {
5.    if(numbers[i]<40)
6.    {
7.       isAll = false;
8.       break;
9.    }
10. }
Now, using the “All” operator:
1. int[] numbers = {2,3,5,8,12,29};
2. bool isAll = numbers.All (n => n < 40);
The All operator will go through each number in the collection and keep track if everyone of the element is meeting the condition of < 40, if so the isAll variable will be set to true, if any number does not match, the result with be false.

Take Operator

The preceding two operators Any and All typically work on a collection and either returns a boolean true or false as a result. So, do LINQ operators only do conditional actions? No, they do more than that. Let's take the Take example here, it does a totally different action.

The Take operator is responsible for selecting the first specified number of elements from the given collection. Think of a SalesPerson collection that has, let's say, 50 elements in the order of the highest to the lowest individuals with Sales figures and you need to find the top 3 individuals.
1. int[] numbers = {2,3,5,8,12,29};
2. int[] top3 = new int[3];
3. for(int i=0;i<3;i++)
4. {
5.    top3[i] = numbers[i];
6. }
Now using the “Take” operator:
1. int[] numbers = {2,3,5,8,12,29};
2. int[] top3 = new int[3];
3. top3 = numbers.Take(3).ToArray();
As you can see, the “Take” operator makes it very easy to go through the collection and it takes the first 3 numbers 2, 3 and 5 and copies them to the top3 array using the ToArray() method. There are many more great operators available with the LINQ, my next part of this series explains some more.

I hope this post gets you excited to try out some LINQ magic if you have not done so. Please feel free to regularly check my blog for new articles and tutorials. Happy LINQing. :)

Recommended Free Ebook
Similar Articles