DEV Community

Cover image for Learning LINQ with 101 Examples and Sample Data (Query & Fluent Syntax)
Jose Maria Iriarte
Jose Maria Iriarte

Posted on • Updated on

Learning LINQ with 101 Examples and Sample Data (Query & Fluent Syntax)

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

The repo in question is as follows:

GitHub logo tigerbluejay / FullLINQ101Implementations

101 LINQ Queries with Complete Classes - Full LINQ 101 Query Implementations

Full LINQ 101 Implementations

This project is a fork of the original 101 LINQ Examples by Microsoft.

The 101 LINQ Examples by Microsoft is a collection of queries that demonstrate the full power of LINQ syntax. These examples utilize mainly query style syntax and some times, when there is no alternative, fluent syntax.

This project maintains the core queries intact except for some variable renaming to improve readability, and its main contribution is the addition of relevant models such as Product, Order and Customer, which should allow you understand how queries work when using custom classes.

Thus, there are now method definitions initializing classes with data which map to the empty method calls in the original examples.

In addition, fluent syntax alternatives have been appended to the original queries provided by Microsoft, which have been modified to be comments where appropriate.

Project Organization

The project is organized…

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:

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();
Enter fullscreen mode Exit fullscreen mode

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:

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();
Enter fullscreen mode Exit fullscreen mode

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:

   internal class Product
    {
        public string ProductName { get; set; }
        public int UnitsInStock { get; set; }
        public decimal UnitPrice { get; set; }
    }
Enter fullscreen mode Exit fullscreen mode

And within the example, I initialized the list with dummy data.

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;
}
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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:

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();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)