Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Select Vs .Include Vs .Select Many

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); 
like image 930
john Gu Avatar asked Jul 09 '13 09:07

john Gu


2 Answers

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.

like image 79
MarcinJuraszek Avatar answered Sep 20 '22 20:09

MarcinJuraszek


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
like image 22
Jonas W Avatar answered Sep 20 '22 20:09

Jonas W