Home >Backend Development >C++ >LINQ Select vs. SelectMany: How Do They Differ When Flattening Nested Collections?

LINQ Select vs. SelectMany: How Do They Differ When Flattening Nested Collections?

Susan Sarandon
Susan SarandonOriginal
2025-01-28 17:46:08994browse

LINQ Select vs. SelectMany: How Do They Differ When Flattening Nested Collections?

Linq Selectmany: The difference between the flat nested collection

Many developers often confuse the differences between

and

methods when learning Linq to SQL. This article will explain their differences clearly through a Linq to SQL example. Select SelectMany The method is used to convert each element in the sequence and generates a new sequence containing the conversion element. The method acts on the sequence of the sequence, and it flattes it into a single sequence by returning the elements in the norm sequence.

The following is a Linq to SQL example: Select SelectMany

In this example,

contains a series of lists, each list represents a person's phone number.

The method flattes this nested structure and generates
<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; }
}

IEnumerable<Person> people = new List<Person>();

// Select 获取一个电话号码列表的列表。
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);

// SelectMany 将列表扁平化成单个电话号码。
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);

// 使用带 resultSelector 参数的重载方法连接父项和子项数据:
var directory = people
    .SelectMany(p => p.PhoneNumbers,
                (parent, child) => new { parent.Name, child.Number });</code>
, which contains only a single phone number.

phoneLists In addition, we can also use the SelectMany parameter in the phoneNumbers heavy load method, which contains the information of the parent object (Person) in the result. Therefore,

Variables store a list of anonymous objects, which contain the person's name and phone number.

SelectMany This comprehensive example demonstrates the basic difference between resultSelector and directory methods in Linq to SQL.

Single elements in the conversion sequence, and

flat nlicing sequences, thereby providing greater flexibility in the operation data structure. Select

The above is the detailed content of LINQ Select vs. SelectMany: How Do They Differ When Flattening Nested Collections?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn