Linq select new
The Select
method in LINQ!
Select
is a LINQ method that allows you to project an existing collection of objects into a new collection of objects. It's a powerful way to transform and shape your data.
Here's the basic syntax:
var result = source.Select(x => new { /* properties */ });
In this example:
source
is the original collection of objects.x
is an element from thesource
collection.new { /* properties */ }
is the new object that will be created for each element in thesource
collection.
The Select
method takes a lambda expression as an argument, which defines the transformation from the original object to the new object. The lambda expression is executed for each element in the source
collection, and the resulting objects are collected in a new collection.
Here are some examples:
Example 1: Selecting a subset of properties
var customers = new[] { new { Id = 1, Name = "John", Email = "[email protected]" },
new { Id = 2, Name = "Jane", Email = "[email protected]" } };
var result = customers.Select(c => new { c.Name, c.Email });
In this example, we select only the Name
and Email
properties from each customer object and create a new collection of anonymous objects with these properties.
Example 2: Selecting a new object with calculated properties
var orders = new[] { new { Id = 1, CustomerId = 1, Total = 100 },
new { Id = 2, CustomerId = 1, Total = 200 },
new { Id = 3, CustomerId = 2, Total = 50 } };
var result = orders.Select(o => new { CustomerName = "Customer " + o.CustomerId, Total = o.Total });
In this example, we select a new object with two properties: CustomerName
and Total
. The CustomerName
property is calculated by concatenating a string with the CustomerId
property, and the Total
property is taken from the original orders
collection.
Example 3: Selecting a new object with a different type
var customers = new[] { new { Id = 1, Name = "John", Email = "[email protected]" },
new { Id = 2, Name = "Jane", Email = "[email protected]" } };
var result = customers.Select(c => new CustomerSummary { Name = c.Name, Email = c.Email });
In this example, we select a new object of type CustomerSummary
, which has two properties: Name
and Email
. The CustomerSummary
class is defined elsewhere in your code.
These are just a few examples of what you can do with the Select
method in LINQ. It's a powerful tool that allows you to transform and shape your data in many creative ways!