views:

1241

answers:

3

Hi,

I've been searching the difference between those two but I couldn't find actually what I want. I need learn the difference when using LINQ To SQL but they all gave me standard array examples.

Can some one give a LINQ TO SQL Example to show the difference between Select and Select Many.

Thanks in advance.

+1  A: 

I understand SelectMany to work like an join shortcut.

So you can:

var orders = customers
             .Where(c => c.CustomerName == "Acme")
             .SelectMany(c => c.Orders);
Nathan Koop
+3  A: 

SelectMany() lets you collapse a multidimensional sequence in a way that would otherwise require a second Select() or loop.

EDIT: since I'm apparently unable to craft a legal LINQ query when I haven't eaten, I'll defer to this blog post to explain further.

Michael Petrotta
But the first one return Enumerables type of Children the second example return type of Parents ? Actually I am little bit confused,would you open it up little bit more ?
Braveyard
Other way around, actually. The second will completely flatten the hierarchy of enumerables, so that you get Children back. Try the article at the link I added, see if that helps.
Michael Petrotta
The first one does not appear to be legal. I think the poster got confused himself. The second one would return an enumerable of parents.
mquander
Thanks, well actually yeah the examples were kinda confusing tho :) but thanks again for trying to help me.
Braveyard
+19  A: 

SelectMany flattens queries that return lists of lists. For example

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);
Mike Two
Thanks, this is one very clear and explanatory.
Braveyard