Exploring LINQ in C# : Querying Made Easy

Jiyan Epözdemir
5 min readMar 30, 2024

--

In the early days of C# programming, navigating through data used to be like walking through a maze blindfolded. Traditional methods often involved crafting intricate queries using separate languages for each data source, leading to code that is difficult to manage and prone to errors.

Also, queries against data are written as plain strings that lack IntelliSense assistance and type verification at compile time. Whether it was SQL queries for databases or XPath expressions for XML documents, developers had to become proficient in different query languages to extract the desired information.

But with LINQ, all of that changed. LINQ offers a unified approach to querying data, regardless of its origin. The days of creating complex, prone to errors code for each data source are long gone. Instead, LINQ provided a consistent and user-friendly syntax for expressing queries, making the process both efficient and accessible.

LINQ offers a unified approach to querying data, allowing developers to use a single, consistent syntax for querying collections, arrays, databases, and more. By integrating query capabilities directly into the C# language, LINQ provides developers with powerful tools for expressing complex queries in a clear and concise manner, with the added benefits of IntelliSense assistance and compile-time type verification.

In this blog post, we’ll explore the fundamentals of LINQ (Language Integrated Query) and how it simplifies data querying in C# development. We’ll delve into the syntax and semantics of LINQ queries, showcasing how they can be used to extract insights from various data sources.

What is LINQ?

LINQ, or Language Integrated Query, is a powerful feature in C# that allows you to query and manipulate data from different data sources using a SQL-like syntax directly within your C# code. It provides a consistent model for querying and transforming data, whether it’s collections, arrays, XML, databases, or any other data source.

Why use LINQ?

  1. Readable code: LINQ queries are concise and expressive, making your code more readable and maintainable.
  2. Type safety: LINQ is strongly typed, ensuring type safety at compile time.
  3. Performance: LINQ queries are optimized by the compiler and runtime, often resulting in efficient execution.
  4. Integration: LINQ seamlessly integrates query capabilities into C# language syntax, eliminating the need for separate query languages.

Getting Started with LINQ

Let’s dive into some simple examples to understand how LINQ works:

Suppose we have a list of products with their names and prices.

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

class Program
{
static void Main(string[] args)
{
var products = new List<Product>
{
new Product { Name = "Laptop", Price = 1200 },
new Product { Name = "Phone", Price = 800 },
new Product { Name = "Tablet", Price = 500 },
new Product { Name = "Headphones", Price = 150 },
new Product { Name = "Mouse", Price = 50 }
};
}
}

class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}

Filtering Data

Let’s say we want to filter products with prices above 200:

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

class Program
{
static void FilterProducts(List<Product> products)
{
var filteredProducts = products.Where(p => p.Price > 200);

foreach (var product in filteredProducts)
{
Console.WriteLine(product.Name);
}
}
}

In this example, Where is a LINQ extension method that filters the elements of the array based on the given condition (p.Price > 200).

Output:

Laptop
Phone
Tablet

Projecting Data

Then, let’s print all product names in capital letters:

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

class Program
{
static void PrintProducts(List<Product> products)
{
var upperCaseNames = products.Select(p => p.Name.ToUpper());

foreach (var name in upperCaseNames)
{
Console.WriteLine(name);
}
}
}

Note that, Select is used to project each element of the array into a new form (in this case, converting each product name to uppercase).

Output:

LAPTOP
PHONE
TABLET
HEADPHONES
MOUSE

Ordering Data

Let’s list the products sorted by alphabetically according to their names:

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

class Program
{
static void SortProducts(List<Product> products)
{
var orderedProducts = products.OrderBy(p => p.Name);

foreach (var product in orderedProducts)
{
Console.WriteLine(product.Name);
}
}
}

In this example, OrderBy sorts the elements of the array in ascending order based on the specified key (in this case, the product’s name). Outputs should be like below :

Output:

Headphones
Laptop
Mouse
Phone
Tablet

Aggregating Data

Let’s say we need to calculate the total price of all products in the list:

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

class Program
{
static void GetTotalPrice(List<Product> products)
{
var total = products.Sum(p => p.Price);

Console.WriteLine("Total= " + total); // Output: Total= 2700
}
}

Sum calculates the sum of all product prices in the list.

Grouping Data

Assume that we want to group products by price range:

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

class Program
{
static void GroupProducts(List<Product> products)
{
var groupedProducts = products.GroupBy(p => GetPriceRange(p.Price));

foreach (var group in groupedProducts)
{
Console.WriteLine($"Price Range: {group.Key}");
foreach (var product in group)
{
Console.WriteLine($"- {product.Name}: ${product.Price}");
}
Console.WriteLine();
}
}

static string GetPriceRange(decimal price)
{
if (price <= 100)
return "Cheap";
else if (price <= 500)
return "Moderate";
else
return "Expensive";
}
}

In this example, GroupBy groups the elements of the list based on the result of the GetPriceRange function, which categorizes products into different price ranges. Outputs should be like below :

Price Range: Expensive
- Laptop: $1200
- Phone: $800

Price Range: Moderate
- Tablet: $500
- Headphones: $150

Price Range: Cheap
- Mouse: $50

Conclusion

LINQ is a powerful tool in the C# developer’s arsenal, offering a clean and efficient way to query and manipulate data. By leveraging LINQ, you can write concise and expressive code that is easy to understand and maintain. If you’re not already using it, start incorporating LINQ into your C# projects today and experience the benefits firsthand!

Sample codes used here are available in the following GitHub repository:

Thank you for reading!

If you found this post helpful, don’t forget to give it a clap and share it with others who might benefit from it.👏👏👏👏👏

References

https://learn.microsoft.com/en-us/dotnet/csharp/linq

--

--

Jiyan Epözdemir

I am a multi-disciplined Software Architect and Computer Engineer, MSc. I enjoy building awesome softwares & applications.