I found the following example regarding the differences between .Select & .SelectMany
public class PhoneNumber
{
public string Number { get; set; }
}
public class Person
{
public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
}
IEnumerable<Person> people = new List<Person>();
// Select gets a list of lists of phone numbers
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);
// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
But i can not actually understnad exaclty what is the difference between (Select gets a list of lists of phone numbers , while, SelectMany flattens it to just a list of phone numbers.).
Seond question , what is the difference between writing:-
people.Select(p => p.PhoneNumbers);
&
people.Include(p => p.PhoneNumbers);
Select gets a list of lists of phone numbers , while, SelectMany flattens it to just a list of phone numbers.
That's exactly the difference. SelectMany
takes a collection of collections and return all items as one collection.
people.Select(p => p.PhoneNumbers);
Select only the phone numbers.
people.Include(p => p.PhoneNumbers);
Select people entities with phone numbers loaded.
You have already answered your first question. =)
The : people.Include(x=>x.PhoneNumbers)
Will load the phonenumbers in the peoples. If you are not doing this, the people.PhoneNumber will be null and not loaded.
So this statement will not execute since PhoneNumbers is null and not loaded :
var phonenumbers = db.peoples.First().PhoneNumbers;
//phonenumbers = null
But if you do like this :
var phonenumbers = db.peoples.Include(x=>x.PhoneNumbers).First().PhoneNumbers;
//phonenumbers will now be a IEnumerable with Phonenumbers
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