How to use projections in C#

By FoxLearn 1/3/2025 7:22:31 AM   68
Projections in C# allow you to transform an object into a new form by selecting only the properties you need.

What is projection in C#?

Projection in C# involves transforming an object into a new form that contains only the properties you need. LINQ supports two main projection operators: Select and SelectMany.

Project Using the Select Operator in C#

Here’s an example of how to use the Select operator to project specific properties from a collection of objects in C#.

Start by defining a class representing a Book:

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public double Price { get; set; }

    public Book(int id, string title, string author, double price)
    {
        this.Id = id;
        this.Title = title;
        this.Author = author;
        this.Price = price;
    }
}

Then, create a list of books and use the Select operator to project only the titles of the books:

var books = new List<Book>
{
    new Book(1, "C# Programming", "John Doe", 29.99),
    new Book(2, "Mastering LINQ", "Jane Smith", 35.50),
    new Book(3, "ASP.NET Core", "Samuel Lee", 40.00),
    new Book(4, "Data Structures", "Emily Davis", 25.75)
};

foreach (var title in books.Select(b => b.Title))
{
    Console.WriteLine(title);
}

Output:

C# Programming
Mastering LINQ
ASP.NET Core
Data Structures

In this example, the Select operator is used to retrieve and display only the titles of the books from the books list. You can easily modify this to project other properties or perform additional operations, such as filtering or calculations, as needed.

Project to anonymous types in C#

You can project multiple properties from a data source into an anonymous type, which is a powerful feature in C#.

var projectedData = books.Select(b => new { b.Title, b.Author });

foreach (var book in projectedData)
{
    Console.WriteLine($"Title: {book.Title}, Author: {book.Author}");
}

Project Using the SelectMany Operator in C#

The SelectMany operator in C# is used to query data from collections that implement the IEnumerable interface. It is useful when you want to flatten multiple collections into a single sequence. While Select produces a single result for each item in a collection, SelectMany concatenates the results from each item into a flattened, combined sequence.

// Extracting distinct subjects
var data = books.SelectMany(b => b.Author).Distinct();

foreach (var subject in data)
{
    Console.WriteLine(subject);
}

Use the Where operator to filter result data in C#

You can use the Where operator after SelectMany to refine and filter the resulting data set.

// LINQ query to filter books where the author's address contains "UK" and the title starts with "T"
var filteredBooks = books
    .Where(b => b.Author.Contains("Smith"))  // Filter by author's
    .Where(b => b.Title.StartsWith("T"))     // Filter by book title starting with "T"
    .Select(b => new { b.Title, b.Author }); // Select relevant fields: Title and Author

// Print the results
foreach (var book in filteredBooks)
{
    Console.WriteLine($"{book.Title} by {book.Author}");
}

Projections in EF Core allow you to retrieve only the necessary columns from the database, optimizing data retrieval.