How to use projections in C#

Take advantage of projections in C# to transform an object into a new form that has only the properties you need

How to use projections in C#
Getty Images

Projection is an operation that transforms the results of a query. You can use projection to transform an object into a new form that has only those properties needed in your application. In this article, we’ll look at how we can work with projections in C#.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core Console Application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.
  7. This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project in the subsequent sections of this article.

What is projection in C#?

Projection refers to the act of transforming an object into a new form such that the newly created object contains only the properties that will be used. Language Integrated Query (LINQ) provides support for two standard query projection operators, Select and SelectMany.

You can use the Select and SelectMany operators to project a single property, or project the results of a query, or project multiple properties from a data source into an anonymous type. You can even perform calculations, filtering, or any other operations on a projection as needed.

In the sections that follow we'll examine how we can work with these operators in C#.

Project using the Select operator in C#

Write the following code inside the Program.cs file.

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public Author(int id, string firstName,
    string lastName, string address)
    {
        this.Id = id;
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Address = address;
    }
}

The following code snippet illustrates how you can take advantage of the Select operator to query data.

var authors = new List<Author>
{
   new Author(1, "Joydip","Kanjilal", "Hyderabad, INDIA"),
   new Author(2, "Anand","Naraswamy", "Cochin, INDIA"),
   new Author(3, "Steve","Smith", "Ohio, USA"),
   new Author(4, "Uday","Denduluri", "London, UK")
};
foreach(var name in authors.Select(e => e.FirstName))
{
   Console.WriteLine(name);
}

When you execute the code snippet above, the first names of all of the authors will be displayed at the console window.

Project to anonymous types in C#

You can project more than one property from a data source, you can even project to an anonymous type as well. The following code snippet illustrates how you can project multiple properties into an anonymous type.

var data = authors.Select(e => new { e.FirstName, e.LastName });

Project using the SelectMany operator in C#

You can take advantage of the SelectMany operator to query data from a collection that implements the IEnumerable<T> interface. You can use the SelectMany operator when you want to query data from several collections and project or flatten them into a single sequence.

Note that both Select and SelectMany produce a result from source values. While Select produces a single result from each source value, SelectMany produces a concatenated sub-collection from each source value.

Let’s now include an extra property in the Author class named Subjects. This property is a list of strings that contain the names of the subjects the author writes books about.

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public List<string> Subjects { get; set; }
        public Author(int id, string firstName, string lastName,
        string address, List<string> subjects)
        {
            this.Id = id;
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Address = address;
            this.Subjects = subjects;
        }
    }

You can use the following code snippet to create a list of authors.

var authors = new List<Author>
{
    new Author(1, "Joydip","Kanjilal", "Hyderabad, INDIA",
    new List<string>{"C#", "F#"} ),
    new Author(2, "Anand","Naraswamy", "Cochin, INDIA", 
    new List<string>{"C#", "VB.NET"}),
    new Author(3, "Steve","Smith", "Ohio, USA", 
    new List<string>{"C#", "C++"}),
    new Author(4, "Uday","Denduluri", "London, UK", 
    new List<string>{"C#", "VB.NET"}),
    new Author(5, "Jane","Barlow", "London, UK", 
    new List<string>{"C#", "C++"})
 };

And you can use the code snippet below to retrieve the names of the programming languages the authors write books about.

var data = authors.SelectMany(a => a.Subjects).Distinct();
foreach (var subject in data)
{
    Console.WriteLine(subject);
}

Use the Where operator to filter result data in C#

You can apply the Where operator after SelectMany to filter the result set. The following code snippet when executed displays the FirstName and the Subject of the author whose FirstName starts with the character “J” and resides in the U.K.

var data = authors
.Where(a => a.Address.IndexOf("UK") >= 0)
.SelectMany(a => a.Subjects, (a, Subject) => new { a.FirstName, Subject })
.Where(n => n.FirstName.StartsWith("J"));
foreach(var author in data)
{
    Console.WriteLine(author);
}

When you execute the above code snippet, you should see the output in the console window as shown in the screen image below.

where operator output c sharp IDG

Projections can be used when working with EF Core, so you can retrieve only the columns from the underlying database you need for your application. In a future article here, I will discuss some advanced operations using projections such as one-to-many projections, results filtering, and ordering.

Copyright © 2020 IDG Communications, Inc.