"Select"和"SelectMany"的区别

27 浏览
0 Comments

"Select"和"SelectMany"的区别

我一直在寻找 SelectSelectMany 之间的区别,但我没有找到合适的答案。我需要了解在使用 LINQ To SQL 时二者的区别,但我找到的都是标准的数组例子。

可以有人提供一个 LINQ To SQL 的例子吗?

admin 更改状态以发布 2023年5月22日
0
0 Comments

选择多个(Select many)类似于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 animals = new List() { "cat", "dog", "donkey" };
List number = new List() { 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)}

0
0 Comments

SelectMany方法用于展开返回列表的列表的查询,例如:

public class PhoneNumber
{
    public string Number { get; set; }
}
public class Person
{
    public IEnumerable PhoneNumbers { get; set; }
    public string Name { get; set; }
}
IEnumerable people = new List();
// Select gets a list of lists of phone numbers
IEnumerable> phoneLists = people.Select(p => p.PhoneNumbers);
// SelectMany flattens it to just a list of phone numbers.
IEnumerable 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 上查看演示

0