Projection Query Operators

Select:

This method is used to transform each element of the query elements into the output sequence that contains the same number of transformed elements, based on a projection function that we specify. 

Example 1:

C#




using System;
using System.Linq;
  
public class GFG{
  
    static public void Main (){
        // Define a list of integers
        var numbers = new List<int> { 1, 2, 3, 4, 5 };
  
        // Use the Select method to project the elements of the list
        // into a new form, by applying a transformation to each element
        var squaredNumbers = numbers.Select(x => x * x);
  
        // Output the elements of the transformed query
        foreach (var num in squaredNumbers)
        {
            Console.WriteLine(num);
        }
    }
}


Output:

 

SelectMany:

This method is used to flatten the elements of a LINQ query that contains sequences or collections of elements. The SelectMany method applies to each element in the query and flattens into a single sequence.

Example 2:

C#




using System;
using System.Linq;
  
public class GFG{
  
    static public void Main (){
  
        // Define a list of lists of integers
        var numbers = new List<List<int>>
        {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 5, 6 },
            new List<int> { 7, 8, 9 },
        };
  
        // Use the SelectMany method to flatten the lists of integers
        // into a single sequence of integers
        var flattenedNumbers = numbers.SelectMany(x => x);
  
        // Output the elements of the flattened query
        foreach (var num in flattenedNumbers)
        {
            Console.WriteLine(num);
        }
    }
}


Output:

 

LINQ Operators and Methods for Transforming Data

LINQ (Language Integrated Query) is a set of language and rich library features provided by C# for writing consistent and intuitive syntax for querying data from various data sources, such as arrays, lists, collections, dictionaries, databases, and more in a type-safe and expressive way.

Some of the important functions of LINQ are:

  • Filtering
  • Sorting
  • Transforming
  • Grouping
  • Joining
  • Aggregation

In this article, we shall have detailed insights into the set of methods or query operators that can be used to transform the elements of a LINQ query from one type to another. These methods allow us to perform operations such as projection, restriction, partitioning, and conversion on the data in our queries.

Following are some of the methods that are used in transforming the data using LINQ:

Similar Reads

Projection Query Operators

Select:...

Restriction Query Operator

...

Partitioning Query Operators

...

Set Operator

Where:...