Codementor Events

C# and LINQ - Part 2 - Getting Started

Published Jun 25, 2021
C# and LINQ - Part 2 - Getting Started

How do I get started?

Download any one of these three IDE/Clients to begin. For this tutorial, I'll be using Visual Studio 2019 Community.

  • Visual Studio
  • Visual Studio Code
  • LINQPad

Note: I am super partial to Visual Studio or Visual Studio Code for a couple of reasons. First, you get all of the Code Completion (a/k/a Intelisense) functionality with those two editors easily at no cost. Second, I've used Visual Studio professionally for close to 20 years now, so it's the one I'm most familiar with (and the one very widely used at a professional level).

Lastly - this primer is made with the understanding that you should have some exposure to both the C# language, some basic knowledge of Object Oriented Programming (OOP), and some beginning understanding of SQL.

Create a new .NET Core project.

Let's create a sandbox console application. A sandbox application is a great way to have an area for you to try "proof of concept" coding on an application that is setup to run right out of the box. Ensure that you select a .NET Core or .NET 5.0 framework to run, and I'd suggest placing your code into a folder that you can push up into GitHub, Bitbucket, or whereever you wish to keep code.

alt

You should see code that looks like the following:

using System;

namespace LinqSandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Create a reference to the System.Linq Namespace

Now, below your using that references the System namespace, create the following references:

using System.Linq;
using System.Collections.Generic;

Why do this? Well, before we get into coding any LINQ, we have to be able to reference the appropriate namespace that contains the LINQ classes. We're including the System.Collections.Generic namespace as it is quite often used along with LINQ to manipulate collections of data.

Your code should look like this now:

using System;
using System.Linq;
using System.Collections.Generic;

namespace LinqSandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Now, you have a very simple console application that should run without any errors. Next, let's dig into a very high level of understanding how LINQ works.

LINQ methods

Understanding the data is important when using LINQ because you have to know what you're looking for. The same is true for when you are going to write SQL queries.
Fortunately, LINQ methods work a lot like SQL query statements. Let's demonstrate some of this now.

In our sandbox, right above the Console.Writeline("Hello World"), let's type out the following:

string testString = "abcdefghijklmnopqrstuvwxyz";

This creates a string variable that contains the simple alphabet. We know this about the data:

  • There are only 26 letters.
  • All the letters are lowercased.
  • There are no special characters or numbers.
  • There are 5 vowels and 21 consonants. (Who am I, Pat Sajak?!?)

A string variable in C# is made up of individual characters. Each character is part of the char struct. Put a bunch of apprpriate chars together, you get a string.

What if I wanted to get the number of letters in the variable? I could do a loop of some sort and count the number of chars individually:

int count = 0;

foreach(char i in testString)
{
  if (char.IsLetter(i))
    count++;
}

To do this, however, I'd need to create ANOTHER variable to hold the count, and then I'd have to wait for the loop to get done. Like someone once said:

alt

Let's use LINQ to do the work for us!

Instead of doing the above, let's use LINQ to get a count of chars for us instead.
We'll replace our lines of code above with one line of code, using the LINQ method Count:

//This gets a count of characters in testString and returns it as an integer.
var numLetters = testString.Count();

alt

This should return the number 26 to us. We can then return this number as part of an output to the console:

Console.WriteLine("Number of Letters in testString is: " + numLetters);

alt

The most efficient way to code this is to just call the method in the Console.WriteLine statement:

Console.WriteLine("Number of Letters in testString is: " + testString.Count());

Lastly, let's put a couple lines of code that will stop the console application from completing unless the end user presses a button:

So now, your code should look similar to this:

using System;
using System.Linq;
using System.Collections.Generic;

namespace LinqSandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            string testString = "abcdefghijklmnopqrstuvwxyz";
            //This gets a count of characters in testString and returns it as an integer.
            Console.WriteLine("Number of Letters in testString is: " + testString.Count());
            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
            Console.WriteLine("Hello World!");
        }
    }
}

Let's run the program, and see what we get, shall we? If you are using Visual Studio, let's insert a breakpoint on the last writeline that types "Hello World" to the console. To do that, use your map to click in the margin to the left of your code:

alt

Lastly, press the F5 button to build and debug the program and show the results:

alt

Discover and read more posts from Alex Horton
get started