Using LINQ to Select and Project Data
LINQ
26 Articles
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
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
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
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.