What is the use of "select" operator in LINQ?
The Select
operator in LINQ is used to transform or project the elements of a collection or sequence into a new form. It allows you to create a new sequence where each element represents a modified or selected version of the original elements. This is particularly useful when you want to extract specific properties or apply a transformation to the data within a collection.
Syntax: 'IEnumerable<TResult> result = sequence.Select(element => expression);'
-
sequence
: The original sequence on which the Select operator is applied.
-
element
: Represents each element in the original sequence.
-
expression
: Specifies the transformation or projection logic to be applied to each element.
-
TResult
: The type of elements in the resulting sequence.
Here's a complete source code example to illustrate the usage of the
Select
operator along with its output:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Define a class for Product
class Product
{
public string Name { get; set; }
public double Price { get; set; }
}
// Create a list of products
List products = new List
{
new Product { Name = "Laptop", Price = 1000 },
new Product { Name = "Mouse", Price = 20 },
new Product { Name = "Keyboard", Price = 30 },
};
// Use LINQ to select only the product names
var productNames = products.Select(product => product.Name);
Console.WriteLine("Original list of products:");
foreach (var product in products)
{
Console.WriteLine($"Name: {product.Name}, Price: ${product.Price}");
}
Console.WriteLine("\nSelected list of product names:");
foreach (var name in productNames)
{
Console.WriteLine($"Product Name: {name}");
}
}
}
Output:
Original list of products:
Name: Laptop, Price: $1000
Name: Mouse, Price: $20
Name: Keyboard, Price: $30
Selected list of product names:
Product Name: Laptop
Product Name: Mouse
Product Name: Keyboard
In this example, we define a Product
class with properties for Name and Price. We create a list of Product
objects called Product
s. Using the Select
operator in LINQ, we project only the product names into a new sequence called productNames
.
The result is a new sequence containing only the product names. As shown in the output, the Select
operator effectively extracts and projects the desired property from each element in the original collection, allowing you to work with a transformed representation of the data.
So, the Select
operator in LINQ is a valuable tool for shaping and extracting data from a collection based on specific criteria, making it easier to work with the selected properties or transformations of the elements.