LINQ (Language Integrated Query) allows you to query data from various sources using a consistent syntax, which can be applied to objects, collections, databases, XML, and more. LINQ supports multiple types of operations, including projection, filtering, and joining, making it a powerful tool for working with data.
In this explanation, we'll focus on query syntax and how to perform projection, filtering, and joining using LINQ queries.
LINQ allows you to write queries using query syntax (which is similar to SQL) or method syntax (using LINQ extension methods). The query syntax provides a more SQL-like approach, which can be easier to understand for people with a background in database query languages.
Here's the general structure of a LINQ query in query syntax:
var query = from variable in collection
where condition
select variable;
Projection is the operation that transforms data into a new shape. In LINQ, you use select to project the elements of a collection into a new format, which can include selecting specific fields or creating new objects.
Imagine you have a collection of Person objects, and you want to project just the names and ages of the people into a new format.
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main()
{
// Sample list of people
List<Person> people = new List<Person>
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Jane", Age = 30 },
new Person { Name = "Mike", Age = 35 }
};
// Projection using query syntax
var projectedData = from person in people
select new { person.Name, person.Age };
foreach (var data in projectedData)
{
Console.WriteLine($"Name: {data.Name}, Age: {data.Age}");
}
}
}
In this example:
select new { person.Name, person.Age } part of the query, which creates anonymous objects containing only the Name and Age properties.Filtering is the process of selecting only those elements that meet a certain condition. You can filter elements in LINQ using the where clause.
Suppose you want to filter the list of people to include only those who are older than 30.
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main()
{
// Sample list of people
List<Person> people = new List<Person>
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Jane", Age = 30 },
new Person { Name = "Mike", Age = 35 }
};
// Filtering using query syntax
var filteredPeople = from person in people
where person.Age > 30
select person;
foreach (var person in filteredPeople)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
In this example:
where clause filters the data to include only people whose Age is greater than 30.Joining is used when you need to combine data from two different collections (e.g., tables, lists) based on a common key. LINQ supports multiple types of joins, such as inner joins and group joins.
Let's say you have two collections: one for Persons and another for Orders. You want to join the two collections to find out which orders were made by which person.
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public int PersonId { get; set; }
public string Product { get; set; }
}
static void Main()
{
// Sample list of people
List<Person> people = new List<Person>
{
new Person { PersonId = 1, Name = "John" },
new Person { PersonId = 2, Name = "Jane" }
};
// Sample list of orders
List<Order> orders = new List<Order>
{
new Order { OrderId = 101, PersonId = 1, Product = "Laptop" },
new Order { OrderId = 102, PersonId = 2, Product = "Smartphone" },
new Order { OrderId = 103, PersonId = 1, Product = "Tablet" }
};
// Inner join using query syntax
var joinQuery = from person in people
join order in orders on person.PersonId equals order.PersonId
select new { person.Name, order.Product };
foreach (var item in joinQuery)
{
Console.WriteLine($"{item.Name} bought {item.Product}");
}
}
}
In this example:
Person and Order collections on the PersonId field using the join keyword.Output:
John bought Laptop
Jane bought Smartphone
John bought Tablet
var leftJoin = from person in people
join order in orders on person.PersonId equals order.PersonId into orderGroup
from order in orderGroup.DefaultIfEmpty()
select new { person.Name, OrderProduct = order?.Product ?? "No Orders" };
var groupJoin = from person in people
join order in orders on person.PersonId equals order.PersonId into orderGroup
select new { person.Name, Orders = orderGroup };
You can combine multiple operations in a single LINQ query. For example, you might want to join two collections, filter the results based on a condition, and then project the result.
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public int PersonId { get; set; }
public string Product { get; set; }
}
static void Main()
{
// Sample list of people
List<Person> people = new List<Person>
{
new Person { PersonId = 1, Name = "John" },
new Person { PersonId = 2, Name = "Jane" },
new Person { PersonId = 3, Name = "Mike" }
};
// Sample list of orders
List<Order> orders = new List<Order>
{
new Order { OrderId = 101, PersonId = 1, Product = "Laptop" },
new Order { OrderId = 102, PersonId = 2, Product = "Smartphone" },
new Order { OrderId = 103, PersonId = 1, Product = "Tablet" }
};
// Combine projection, filtering, and join
var combinedQuery = from person in people
join order in orders on person.PersonId equals order.PersonId
where person.Name.StartsWith("J")
select new { person.Name, order.Product };
foreach (var item in combinedQuery)
{
Console.WriteLine($"{item.Name} bought {item.Product}");
}
}
}
In this combined query:
people and orders collections on the PersonId.Output:
John bought Laptop
John bought Tablet
Jane bought Smartphone
In LINQ, you can use query syntax to perform various operations on data such as:
By using LINQ, you can write cleaner, more readable code for querying and manipulating data in C#.
Open this section to load past papers