8

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); 

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

3 Comments

so what is ment by this "That's exactly the difference. SelectMany takes a collection of collections and return all items as one collection"
Items are the same, but they are flatten into one list. So you don't have List<List<A>> but List<A> made by concatenating items of all inner lists of source.
and what si the idea of having these two different type of collections ?
1

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 

2 Comments

but i can not understnad what is the difference between the two "select gets a list of lists of phone numbers , while, SelectMany flattens it to just a list of phone numbers."
That's the point.. if you just want the phonenumbers and uses select.. You will recieve a IE<IE<PhoneNumber>>, with selectmany you get a IE<PhoneNumber> witch in some cases can be very handy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.