I have read many sites/threads on select and select many in LINQ but still don't quite understand.
Does select return one element in a collection and select many flatten a collection (eg List>())?
Thanks
SelectMany(<selector>) method The SelectMany() method is used to "flatten" a sequence in which each of the elements of the sequence is a separate, subordinate sequence.
In case of Select it you can map to an IEnumerable of a new structure. Where() works as an filter to the IEnumerable, it will return the result on the basis of the where clause.
What is Linq SelectMany? The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.
When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault. When you want a default value if the result set contains no record, use FirstOrDefault.
Here's a sample. Hope it clarifies everything:
static void MethodRun()
{
List<Topping> testToppings = new List<Topping> { Topping.Cheese, Topping.Pepperoni, Topping.Sausage };
var firstLetterofToppings = testToppings.Select(top => top.ToString().First());
// returns "C, P, S"
var singleToppingPizzas = testToppings.Select(top => new Pizza(top)).ToArray();
// returns "Pizza(Cheese), Pizza(Pepperoni), Pizza(Sausage)"
List<Topping> firstPizza = new List<Topping> { Topping.Cheese, Topping.Anchovies };
List<Topping> secondPizza = new List<Topping> { Topping.Sausage, Topping.CanadianBacon, Topping.Pepperoni };
List<Topping> thirdPizza = new List<Topping> { Topping.Ham, Topping.Pepperoni };
List<IEnumerable<Topping>> toppingsPurchaseOrder = new List<IEnumerable<Topping>> { firstPizza, secondPizza, thirdPizza };
var toppingsToOrder = toppingsPurchaseOrder.SelectMany(order => order);
//returns "Cheese, Anchovies, Sausage, CanadianBacon, Pepperoni, Ham, Pepperoni"
}
class Pizza
{
public List<Topping> Toppings { get; private set; }
public Pizza(Topping topping) : this(new List<Topping> { topping }) { }
public Pizza(IEnumerable<Topping> toppings)
{
this.Toppings = new List<Topping>();
this.Toppings.AddRange(toppings);
}
}
enum Topping
{
Cheese,
Pepperoni,
Anchovies,
Sausage,
Ham,
CanadianBacon
}
The key is that Select() can select any type of object. It's true that you can select a property of whatever generic value is assigned to your collection, but you can select any other type of object also. SelectMany() just flattens your list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With