我一直在寻找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 });
选择很多就像SQL中的交叉连接操作一样,它需要交叉产品。
例如,如果我们有
Set A={a,b,c}
Set B={x,y}
选择多个可用于获取以下设置
{ (x,a) , (x,b) , (x,c) , (y,a) , (y,b) , (y,c) }
请注意,这里我们采用可以从集合 A 和集合 B 的元素中进行的所有可能组合。
这是您可以尝试的 LINQ 示例
List<string> animals = new List<string>() { "cat", "dog", "donkey" };
List<int> number = new List<int>() { 10, 20 };
var mix = number.SelectMany(num => animals, (n, a) => new { n, a });
混合物将具有扁平结构的以下元素
{(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}
var players = db.SoccerTeams.Where( c=> c.Country == "Spain")
.SelectMany( c => c.players);
foreach(var player in players)
{
Console.WriteLine( player.LastName);
}
...