我一直在寻找 Select
和 SelectMany
之间的区别,但一直找不到合适的答案。我需要了解使用 LINQ To SQL 时的区别,但我发现的只是标准数组示例。
有人可以提供 LINQ To SQL 示例吗?
最佳答案
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 });
Live Demo on .NET Fiddle
关于c# - Select 和 SelectMany 的区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/958949/