Home >Backend Development >C++ >Select vs. SelectMany in LINQ to SQL: When Should I Use Which?
When using Linq to SQL, it is important to understand the difference between
and. Select
It is used to retrieve a single element from the data set, and SelectMany
The query results used to flatten the nested set. Select
SelectMany
The following examples will explain the differences between the two more clearly:
Assuming we have a
class that contains a attribute, which returns a set of a Person
instance. In order to retrieve all the phone numbers of all personnel, we can use PhoneNumbers
: PhoneNumber
Select
<code class="language-csharp">IEnumerable<Person> people = new List<Person>(); // Select: 返回一个电话号码列表的列表 IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);</code>:
phoneLists
SelectMany
In addition, if we want to include the data of the father
<code class="language-csharp">// SelectMany: 将集合扁平化为一个电话号码列表 IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);</code>heavy load:
Person
SelectMany
By understanding the difference between and
<code class="language-csharp">// 带结果选择器的 SelectMany: 在结果中包含父数据 var directory = people .SelectMany(p => p.PhoneNumbers, (parent, child) => new { parent.Name, child.Number });</code>
The above is the detailed content of Select vs. SelectMany in LINQ to SQL: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!