Introducing LINQ

I know it has been about a long time but I've never really got my blogging game up and running so here is my first attempt at writing one.

LINQ or Language Integrated Querying syntax in C# used for query objects and/or SQL databases.

Useful

This is a useful set of code snippets and brief bits of information about LINQ and what it can be used for, it's not an exhaustive list but it is a handy reference for myself to come back to when I forget what something does or how I should use the LINQ function.

Aggregate

To understand a definition of Aggregate think of it in terms of operating on each element of the list taking into account the previous operations. That is to say, it acts on the first and second elements and carries the result forward. Then it operates on the previous result and the third element and carries forward. etc. You can use aggregate, to sum up, numbers in a collection.

Note here that we have an accumulated value and the next value in the lambda.

var nums = new[] { 1, 2, 3, 4 };
var sum = nums.Aggregate((accumulated, next) => accumulated + next);
Console.WriteLine(sum); // output: 10 (1+2+3+4)

Count

This one is fairly self-explanatory and is used to count the number or items in a list.

IEnumerable<string> items = new List<string> { "A", "B", "C" };
int count = items.Count();  // count: 3

You can also use the Count with predicates like so:

IEnumerable<int> items = new List<int> { 8, 3, 2 };

// these two lines do the same
int count = items.Where(x => x < 5).Count();  // count: 2
int count = items.Count(x => x < 5);          // count: 2

// you can apply functions in the predicate too
IEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" };
// Will return 2
int result = strings.Count(str => str.Contains("then"));

Here is another example with the Linq extension method and with query objects:

int[] intNumbers = new int[] { 60, 80, 50, 90, 10, 30, 70, 40, 20, 100 };

// Using Method Syntax
int numberCount = intNumbers.Count();

// Using Query Syntax
int queryCount = (from num in intNumbers 
    select num).Count();

First

Simply put, if you want to return the First item in an array then you can use this:

int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 };

int first = numbers.First();

If you wanted to return the default for the object in cases where there might be an empty list then you can use FirstOrDefault. You would typically use this when you also have a predicate and potentially you will not have any items that meet its conditions:

int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 };

int first = numbers.FirstOrDefault(x => x > 25);

Select

You can use Select to project your list into something new.

string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

Where

You can use Where to query for items that meet your predicate:

List<string> fruits =
    new List<string> { "apple", "passionfruit", "banana", "mango",
                    "orange", "blueberry", "grape", "strawberry" };

IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6);

// or perhaps like this, its upto you
IEnumerable<string> query = fruits.Where(fruit => fruit.StartsWith("b"));

Zip

This is one I always forget what its for! You can take two sequences though and the way I remember it now is like zipping two sequences together, so you can see in the following code snippet, we have numbers and word arrays and we zip together starting with the numbers array and zipping in the words.

Each function of zip takes an item from the first array and an item from the second array.

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords)
    Console.WriteLine(item);

// This code produces the following output:

// 1 one
// 2 two
// 3 three