Learning LINQ with 101 Examples and Sample Data (Query & Fluent Syntax)
Tags: beginners, tutorial, github, csharp
Published: 2022-10-19 22:45:22

One of the most useful skills you can learn as a .NET developer is **LINQ (Language-Integrated Query) syntax**. With LINQ you can _query collections like lists and arrays_.

I forked a project from **Microsoft’s official 101 LINQ examples**, adding data so that you can now see what is being queried and can make better sense of the results.

I also gave variables more meaningful names. This should help you read query syntax better.

This repo is _ideal for beginners with a basic understanding of C#  syntax_ who also want to learn LINQ

To get started, clone the repository to get it in your local computer. Doing so is easy. Instructions are provided in the following link:

[How to clone a repository](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)

The repo in question is as follows:

{% github tigerbluejay/FullLINQ101Implementations %}

You’ll find the Solution contains **14 projects**, each dealing with a different type of query. 

Each project contains a number of LINQ examples.

A sample query with some context is as follows:

```csharp
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var lowNumbers = from number in numbers
                 where number < 5
                 select number;

Console.WriteLine("Numbers < 5:");
foreach (var lowNumber in lowNumbers)
{
    Console.WriteLine(lowNumber);
}
Console.ReadKey();
```
Simply,

- We have an int array with the name "numbers".
- The query evaluates every number from the numbers array.
- The query then selects the numbers that match the condition of being less than 5.
- The new collection is saved into var lowNumbers.
- var lowNumbers can then be iterated, printing to the console each number.

This is straightforward and requires solely the effort of getting used to LINQ query syntax. 

So not too complicated. But what do you do if you are working with lists and not arrays?

This is where this repo is useful.

Consider querying a list:

```csharp
List<Product> products = GetProductList();

var soldOutProducts = from product in products
                      where product.UnitsInStock == 0
                      select product;

Console.WriteLine("Sold out products:");
foreach (var soldOutProduct in soldOutProducts)
{
    Console.WriteLine($"{soldOutProduct.ProductName} is sold out!");
}
Console.ReadKey();
```
The example is similar to the array example above. Only this time we are iterating not through an explicit array but through a list and finding products where UnitsInStock are 0.

To aid you in verifying your understanding of the query, I have added a definition for the GetProductList() method.

To do so, I first had to define a model within the project, which is as follows:

```csharp
   internal class Product
    {
        public string ProductName { get; set; }
        public int UnitsInStock { get; set; }
        public decimal UnitPrice { get; set; }
    }
```
And within the example, I initialized the list with dummy data.

```csharp
List<Product> GetProductList()
{
    List<Product> productsList = new List<Product>();
    productsList.Add(new Product 
{ ProductName = "Product 1", UnitsInStock = 3, UnitPrice = 3.00m });

    productsList.Add(new Product 
{ ProductName = "Product 2", UnitsInStock = 0, UnitPrice = 4.00m });

    productsList.Add(new Product 
{ ProductName = "Product 3", UnitsInStock = 5, UnitPrice = 6.00m });

    productsList.Add(new Product 
{ ProductName = "Product 4", UnitsInStock = 1, UnitPrice = 1.00m });

    productsList.Add(new Product 
{ ProductName = "Product 5", UnitsInStock = 0, UnitPrice = 2.00m });

    productsList.Add(new Product 
{ ProductName = "Product 6", UnitsInStock = 2, UnitPrice = 1.00m });

    productsList.Add(new Product 
{ ProductName = "Product 7", UnitsInStock = 0, UnitPrice = 7.00m });

    productsList.Add(new Product 
{ ProductName = "Product 8", UnitsInStock = 3, UnitPrice = 8.00m });


    return productsList;
}
```

From the list we see that _products 2, 5 and 7 have 0 UnitsInStock_. Thus, we now know what to expect in the console if we understood the query correctly.

Console output is as follows for that example:

```
Sold out products:
Product 2 is sold out!
Product 5 is sold out!
Product 7 is sold out!
```

And so on and so it goes for all projects. In each project you will find examples defined in Program.cs and then a folder containing the model(s) used in that particular project.

The examples that deal with lists all reference a method where I initialize a list of some sort with dummy data. Just like in the example above.

Although the projects are ordered alphabetically and can be reviewed in any order, it is best to start with the **LINQRestrictionOperators Project**, then the **LINQProjectionOperators Project**, to understand basic _where_ and _select_ clauses. Then move to whichever project interests you the most.

Enjoy!

PS: I've added fluent syntax implementations for the queries where convenient. Where fluent syntax implementations exist, the query syntax version of the queries have been commented.

For example, in the example above, we now have:

```csharp
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

//var lowNumbers = from number in numbers
//                 where number < 5
//                 select number;

var lowNumbers = numbers.Where(number => number < 5).Select(number => number);

Console.WriteLine("Numbers < 5:");
foreach (var lowNumber in lowNumbers)
{
    Console.WriteLine(lowNumber);
}
Console.ReadKey();
```

{% user josemariairiarte %}