Language Integrated Query (LINQ) is a comprehensive library with a variety of methods. In this article, we will discuss what LINQ is and 5 underestimated LINQ methods in .NET 8.
What is LINQ?
LINQ is a powerful query syntax that assists developers in accessing query collections. For instance, I want to access all the users who live in New York, If we write it as an SQL query it will look like
string city = “New York”
string query = $"SELECT * FROM Customers WHERE City = '{city}'";
var command = new SqlCommand(query, connection);
However, it is not the end of accessing the data we need to go for
using (var command = new SqlCommand(query, connection))
{
// Execute the command and use a SqlDataReader to read the results
using (var reader = command.ExecuteReader())
{
// Loop through each row in the result set
while (reader.Read())
{
// Access each column by column name or index
int customerId = reader.GetInt32(0); // By column index
string firstName = reader.GetString(reader.GetOrdinal("FirstName")); // By column name
string lastName = reader.GetString(reader.GetOrdinal("LastName"));
// Process data (for example, print to console)
Console.WriteLine($"ID: {customerId}, Name: {firstName} {lastName}");
}
}
}
With this approach, we not only need to write a ton of code but also expose applications for SQL Injection.
On the other hand, we have another approach which is
string city = “New York”;
var customers = dbContext.Customers.Where(c => c.City == city).ToList();
After ToList() our data will be converted into an enumerable allowing the developer to access each row and a chunk of the data
foreach (var customer in customersList) {
>
Console.WriteLine($"ID: {customer.CustomerID}, Name: {customer.FirstName} {customer.LastName}, City: {customer.City}");
}
5 Underestimated LINQ Methods In .Net 8
Aggregate
In SQL aggregate functions are like mix, max, count, sum & avg but when it comes to the .NET, It has no relation with the SQL aggregate function. In .NET 8 aggregate functions are used for performing cumulative tasks, For instance, I want to know the longest word in my list
var numbers = new List { 1, 2, 3, 4 };
int product = numbers.Aggregate((total, next) => total * next);
Console.WriteLine(product); // Output: 24
Zip
Zip is denoted to combine sometimes as this term is generally used for combing files. As a similar concept is used to provide a similar functionality for instance I have 2 lists and I want to combine them and return a string “1 – One”
var numbers = new List { 1, 2, 3 };
var words = new List { "One", "Two", "Three" };
var zipped = numbers.Zip(words, (n, w) => $"{n} - {w}").ToList();
foreach (var item in zipped)
{
Console.WriteLine(item);
}
// Output:
// 1 - One
// 2 - Two
// 3 - Three
GroupBy
GroupBy can be a useful function as it can help us group the data just like in the example below I have created a few customers with their names and cities and now I want to group the list with the city and return a dictionary/hashmap
var customers = new List
{
new Customer { Name = "Alice", City = "Seattle" },
new Customer { Name = "Bob", City = "Seattle" },
new Customer { Name = "Charlie", City = "Portland" },
};
// Group customers by city and get a list of names for each city
var groupedByCity = customers
.GroupBy(c => c.City, c => c.Name)
.ToDictionary(g => g.Key, g => g.ToList());
foreach (var city in groupedByCity)
{
Console.WriteLine($"{city.Key}: {string.Join(", ", city.Value)}");
}
// Output:
// Seattle: Alice, Bob
// Portland: Charlie
Lookup
Lookup is also quite similar to the groupBy just the difference is with ToDictionary(g => g.Key, g => g.ToList()). However, lookup will create an immutable list, and also lookup is ideal for collection where the group is needed once.
var customers = new List
{
new Customer { Name = "Alice", City = "Seattle" },
new Customer { Name = "Bob", City = "Seattle" },
new Customer { Name = "Charlie", City = "Portland" },
};
// Group customers by city and get a list of names for each city
var groupedByCity = customers
.GroupBy(c => c.City, c => c.Name)
.ToDictionary(g => g.Key, g => g.ToList());
foreach (var city in groupedByCity)
{
Console.WriteLine($"{city.Key}: {string.Join(", ", city.Value)}");
}
// Output:
// Seattle: Alice, Bob
// Portland: Charlie
Except
Except will ignore all the values provided in the list.
var allNumbers = new List { 1, 2, 3, 4, 5 };
var excludeNumbers = new List { 2, 4 };
var result = allNumbers.Except(excludeNumbers).ToList();
foreach (var number in result)
{
Console.WriteLine(number);
}
// Output: 1,3, 5
For more details about the LINQ method please visit here