C# Linq

LINQ Select Operator in C# with Examples

The Select operator is a LINQ query operator that projects each element of a sequence into a new form. The projection is specified by a function that takes an element of the sequence as an input and returns a new element or a new object that contains some or all of the properties of the input element.

The Select operator is typically used to transform the elements of a sequence into a new form or to extract a subset of the properties of the elements. For example, you can use the Select operator to extract the names of the people in a list of Person objects, or to create a new sequence of the squares of a list of integers.

You can also use Select operator to create a new object from the properties of an existing object, for example creating a new anonymous type from the selected properties of a class.

It’s worth noting that the Select operator returns an IEnumerable<T> object, which is a lazy-evaluated sequence, so the query is not executed until the results are enumerated or materialized.

The Select operator is a very powerful tool that can be used in many different ways to transform and shape data in a variety of ways, it’s a fundamental operator that is used extensively in LINQ.

LINQ Select Examples

Example 1: Projecting a list of integers to a list of their squares:

Example 2: Selecting properties of a list of objects:

Example 3: Selecting a subset of properties from a list of objects:

Example 4: Selecting and flattening a nested collection:

Example 5: Selecting and transforming a list of objects into a dictionary:

Example 6: Projecting a list of integers to a list of their squares and cubes:

Example 7: Selecting a specific property from a list of objects and creating a new list of that property, then transforming it into a new form:

Example 8: Selecting a specific property from a list of objects, creating a new list of that property, then grouping it by another property:

Example 9: Selecting a specific property from a list of objects, creating a new list of that property and then sorting it:

Example 10: Selecting a specific property from a list of objects, creating a new list of that property, then using it as a key in a dictionary:

1 Comment

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.