LINQ to SQL: Understanding Select
and SelectMany
Mastering LINQ to SQL requires understanding the key differences between Select
and SelectMany
. Both project data, but their approaches differ significantly.
Select
performs a one-to-one transformation. It takes each element from an input sequence and applies a function to produce a new element in the output sequence. This is ideal for extracting specific properties or performing calculations on individual items.
SelectMany
, on the other hand, flattens a sequence of sequences into a single sequence. This is invaluable when working with hierarchical or nested data structures. It allows you to traverse multiple levels and access the underlying elements.
Let's illustrate with a Person
class containing a collection of PhoneNumber
objects:
<code class="language-csharp">public class PhoneNumber { public string Number { get; set; } } public class Person { public IEnumerable<PhoneNumber> PhoneNumbers { get; set; } public string Name { get; set; } }</code>
Select
Example:
<code class="language-csharp">IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);</code>
This uses Select
to get a sequence of phone number sequences—one for each person. The result remains nested.
SelectMany
Example:
<code class="language-csharp">IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);</code>
SelectMany
flattens the nested structure, producing a single sequence containing all phone numbers from all people.
Combining Parent and Child Data with SelectMany
:
A powerful feature of SelectMany
is its ability to incorporate parent data into the projection. Using the overload with a second parameter, you can create a new object combining parent and child properties:
<code class="language-csharp">var directory = people .SelectMany(p => p.PhoneNumbers, (parent, child) => new { parent.Name, child.Number });</code>
This generates a directory listing each person's name and their associated phone numbers. The output combines data from both the Person
and PhoneNumber
classes.
The above is the detailed content of What's the Difference Between LINQ's Select and SelectMany Operators?. For more information, please follow other related articles on the PHP Chinese website!