Using LINQ to Select and Project Data

Using LINQ to Select and Project Data

linq

14 Articles

Improve

In this article, let's learn about how to use Select in LINQ in .NET.

Note: If you have not done so already, I recommend you read the article on Introducing LINQ in .NET.

Table of Contents

  1. Introduction
  2. TLDR
  3. Complete Object
  4. Single Property
  5. Specific Properties
  6. Build Anonymous Class
  7. Summary

Introduction

We can use LINQ Select to select data within collections. The select clause produces the results of the query and specifies the "shape" or type of each returned element. For example, you can specify whether your results will consist of complete objects, just one member, a subset of members, or some completely different result type based on a computation or new object creation. When the select clause produces something other than a copy of the source element, the operation is called a projection. The use of projections to transform data is a powerful capability of LINQ query expressions.

We can use LINQ Select to shape data and,

  • Select Complete Object
  • Select Single Property
  • Select Specific Properties
  • Select and Build Anonymous Class

TLDR

LINQ Select in .NET

Select Complete Object

The following example shows how to select entire Product class and create a copy of it.

Code Sample - LINQ Select Complete Object

Select Single Property

The following example shows how to select single property of Product class and create a List<string>.

Code Sample - LINQ Select Single Property

Select Specific Properties

The following example shows how to select specific properties from Product class and create a copy of it.

Code Sample - LINQ Select Specific Properties

Select and Build Anonymous Class

The following example shows how to change shape or build an anonymous class and create a copy of it.

Code Sample - LINQ Select and Build Anonymous Class

Demo - LINQ Select Clause Demo

Let's try LINQ Select

  • We have Product class with following properties - Id, Name, Color, Price, Size
  • Enter the column names you would like to select. Columns not selected will have default value
  • Click on select products
  • Click on reset to try other combination
Id Name Color Price Size
1 HL Road Frame Black 1000 58
2 HL Road Frame Red 1000 58
3 HL Road Frame Black 1000 58
4 HL Road Frame Red 1000 58
5 HL Road Frame Brown 1000 58
6 HL Road Frame White 1000 58

Summary

In this article we learn't how to Select data within collection using LINQ. We also learn't how to project the data, change shape, how to select complete object, how to select single property, how to select specific properties and how to build an anonymous class. All these can be used with any IEnumerable or IQueryable types.

  • Linq
  • Select
  • Projection
  • Shape