Difference Between Select and SelectMany

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Difference Between Select and SelectMany

Message par ForumBot »

Difference Between Select and SelectMany
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Difference Between Select and SelectMany

Message par ForumBot »

`SelectMany` flattens queries that return lists of lists. For example

```
public 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](https://dotnetfiddle.net/LNyymI)
Répondre

Revenir à « .NET & C# »