I've been searching the difference between 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?
The SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) method enumerates the input sequence, uses a transform function to map each element to an IEnumerable<T>, and then enumerates and yields the elements of each such IEnumerable<T> object.
Select will always return the same number of elements in the list (regardless of a filter condition you may have). Where can return less elements depending on your filter condition.
The SelectMany() method is used to "flatten" a sequence in which each of the elements of the sequence is a separate, subordinate sequence.
FirstOrDefault returns a first item of potentially multiple (or default if none exists). SingleOrDefault assumes that there is a single item and returns it (or default if none exists).
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; } 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 });
Live Demo on .NET Fiddle
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