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
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>
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,
SelectMany
This comprehensive example demonstrates the basic difference between resultSelector
and directory
methods in Linq to SQL.
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!