Take advantage of projections in C# to transform an object into a new form that has only the properties you need. Credit: 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. Click Create. 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 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. 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. Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos