一尘不染

Select和SelectMany之间的区别

c#

我一直在寻找和之间的区别SelectSelectMany但找不到合适的答案。我需要学习使用LINQ To
SQL的区别,但我发现的只是标准数组示例。

有人可以提供LINQ To SQL示例吗?


阅读 627

收藏
2020-05-19

共1个答案

一尘不染

SelectMany展平返回列表列表的查询。例如

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 gets a list of lists of phone numbers
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);

// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> 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 });

.NET Fiddle上的实时演示

2020-05-19