Method Select

Select() Method

Select() takes each source element, transforms it, and returns a sequence of the transformed values as requested by the condition

Let’s see a query to show only the student cities

List<Student> students = new List<Student>()
{
    new Student("Sam","Mysore"),
    new Student("Ted","Delhi"),
    new Student("Sam","Bangalore"),            
    new Student("Raj","Mumbai"),
    new Student("Adhin","Hyderabad"),
    new Student("Raj","Indore"),            
    new Student("Bhuvan","Chennai"),
    new Student("Sam","Banaras"),
};

var cities = students.Select(s=>s.City);

foreach (string c in cities)
    Console.WriteLine(n);

We can also select a property of each element!

var strings = new List<string> { "one", "two", "three", "four" };
  
var result = strings.Select(str => str.Length);
 
foreach(var x in result)
  Console.WriteLine(x);

SelectMany()

The SelectMany() method is used to "flatten" a sequence in which each of the elements of the sequence is a separate, subordinate sequence.

We can turn a two-dimensional array into a single sequence of values, as shown in this example

int[][] arrays = {
    new[] {1, 2, 3},
    new[] {4},
    new[] {5, 6, 7, 8},
    new[] {12, 14}
};
// Will return { 1, 2, 3, 4, 5, 6, 7, 8, 12, 14 }
IEnumerable<int> result = arrays.SelectMany(array => array); // we can use var as well

Last updated