Projection Operators (LINQ)
Posted by Rajinder
Last Updated: July 23, 2012

Select

This sample uses select to produce a sequence of ints one higher than those in an existing array of ints.

public void Linq6() 
{ 
    int[] numbers = { 5413986720 }; 
  
    var numsPlusOne = 
        from n in numbers 
        select n + 1; 
  
    Console.WriteLine("Numbers + 1:"); 
    foreach (var i in numsPlusOne) 
    { 
        Console.WriteLine(i); 
    } 
}

Select (Example 2)

This sample uses select to return a sequence of just the names of a list of products.

public void Linq() 
{ 
    List<Product> products = GetProductList(); 
  
    var productNames = 
        from p in products 
        select p.ProductName; 
  
    Console.WriteLine("Product Names:"); 
    foreach (var productName in productNames) 
    { 
        Console.WriteLine(productName); 
    } 
}

SelectMany

This sample uses a compound from clause to make a query that returns all pairs of numbers from both arrays such that the number from numbersA is less than the number from numbersB.

public void Linq() 
{ 
    int[] numbersA = { 0245689 }; 
    int[] numbersB = { 13578 }; 
  
    var pairs = 
        from a in numbersA 
        from b in numbersB 
        where a < b 
        select new { a, b }; 
  
    Console.WriteLine("Pairs where a < b:"); 
    foreach (var pair in pairs) 
    { 
        Console.WriteLine("{0} is less than {1}", pair.a, pair.b); 
    } 
}
Related Content