Codementor Events

C# and LINQ - Part 1

Published Jun 20, 2021
C# and LINQ - Part 1

My First Personal Experience with LINQ

When I first started learning to develop in C# many years ago, I came across some code that I was befuddled at. It looked like another language to me, something that I'd seen somewhere in a science fiction movie, or on a NASA video. I decided to talk to one of my mentors about what I had seen, and he looked at me with a very odd look and said, "Man, that's LINQ. Where you been?"

Puzzled, I thought to myself, "The dude from The Legend of Zelda is a coder as well?"

I decided to try to understand what (or who) this LINQ was and what it was all about. It turned out to be one of the better decisions I made in my career, and it opened up a new way of learning for me as I wrote solutions that would interact with various data layers in the future.

W....haaaaat is this LINQ, anyway?

LINQ stands for Language Intergrated Query, or LINQ for short. In a nutshell, LINQ is an extension library in the .NET framework that allows you to utilize different ways to retrieve data from different data sets.

Querying a database and need to put it into C# objects? Use a LINQ query:

void Main()
{
  List<TestClass> Items = new List<TestClass>();
  TestClass listItem;
  
  using (SqlConnection conn = new SqlConnection("<CONNSTRING HERE>"))
  {
    string someSQL = @"SELECT customer_id, first_name, last_name, phone FROM sales.CUSTOMERS (NOLOCK)";
  
    SqlCommand command = new SqlCommand(someSQL, conn);
  
    conn.Open();
  
    using(SqlDataReader reader = command.ExecuteReader())
    {
      while (!reader.IsClosed && reader.Read())
      {
        listItem = new TestClass()
        {
          CustomerID = int.Parse(reader[0].ToString()),
          FirstName = reader[1].ToString(),
          LastName = reader[2].ToString(),
          Phone = reader[3].ToString()
        };
        
        Items.Add(listItem);
      }		
    }
  }

  //SQL to LINQ operations:
  
  //SQL:  SELECT FirstName, LastName, Phone FROM Items where CustomerID <= 10
  var topTen = Items.Where(i => i.CustomerID <= 10).Select(i => new { i.FirstName, i.LastName, i.Phone });
  
  foreach (var item in topTen)
  {
    Console.WriteLine(item);
  }
  
  
}

public class TestClass
{
  public int CustomerID { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Phone { get; set; }	
}

Need to count the number of occurances of a specific letter in a string? Use a LINQ query for it:

string TheString = "supercalifragilisticexpialidocious";

Console.WriteLine(string.Format("Number of I's in {0} is {1}", TheString, 
  TheString.Where(i => i.Equals('i')).Count()));
  
//Number of I's in supercalifragilisticexpialidocious is 7

Learning LINQ without Visual Studio/VS Code? Enter LINQPad!

The cool thing about learning about LINQ is that it doesn't take a very souped up computer to do it! If you go and download a very small client called LINQPad (link is here), you can not only learn how to use LINQ, but you can learn fundamentals of C#, F#, VB.NET, AND SQL all at the same time. It's a wonderful tool, free (although you can pay for advanced debugging and NuGet functionality) and I wish it had been in my life a lot sooner.

LINQ.JPG

Final word about LINQ...

In closing - utilizing LINQ can be one of the greatest tools in a .NET developer's toolbox. Yes, you will hear that LINQ can, at times, be very memory expensive. Along with that, you'll need to know when and when not to use a LINQ query. As Uncle Ben told Peter, "With great power...comes great responsibility."

Discover and read more posts from Alex Horton
get started