Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between Select and SelectMany

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?

like image 661
Tarik Avatar asked Jun 06 '09 03:06

Tarik


People also ask

What is the use of SelectMany?

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.

What is difference between select and where in Linq?

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.

What is SelectMany in Linq?

The SelectMany() method is used to "flatten" a sequence in which each of the elements of the sequence is a separate, subordinate sequence.

What is the difference between SingleOrDefault and FirstOrDefault?

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


1 Answers

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

like image 169
Mike Two Avatar answered Oct 01 '22 10:10

Mike Two