gotchacsharpCritical
Difference Between Select and SelectMany
Viewed 0 times
andbetweenselectmanydifferenceselect
Problem
I've been searching the difference between
Can someone provide a LINQ To SQL example?
Select and SelectMany but I haven't been able to find a suitable answer. I need to learn the difference when using LINQ To SQL but all I've found are standard array examples. Can someone provide a LINQ To SQL example?
Solution
SelectMany flattens queries that return lists of lists. For examplepublic class PhoneNumber
{
public string Number { get; set; }
}
public class Person
{
public IEnumerable PhoneNumbers { get; set; }
public string Name { get; set; }
}
IEnumerable people = new List();
// Select gets a list of lists of phone numbers
IEnumerable> phoneLists = people.Select(p => p.PhoneNumbers);
// SelectMany flattens it to just a list of phone numbers.
IEnumerable phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
// And to include data from the parent in the result:
// pass an expression to the second parameter (resultSelector) in the overload:
var directory = people
.SelectMany(p => p.PhoneNumbers,
(parent, child) => new { parent.Name, child.Number });Live Demo on .NET Fiddle
Code Snippets
public class PhoneNumber
{
public string Number { get; set; }
}
public class Person
{
public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
public string Name { 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);
// And to include data from the parent in the result:
// pass an expression to the second parameter (resultSelector) in the overload:
var directory = people
.SelectMany(p => p.PhoneNumbers,
(parent, child) => new { parent.Name, child.Number });Context
Stack Overflow Q#958949, score: 1995
Revisions (0)
No revisions yet.