我一直在搜索Select和SelectMany之间的区别,但我还没有找到合适的答案。我需要学习使用LINQ to SQL时的差异,但我所找到的都是标准数组示例。

有人能提供一个LINQ到SQL的例子吗?


我理解SelectMany工作起来像一个连接快捷方式。

所以你可以:

var orders = customers
             .Where(c => c.CustomerName == "Acme")
             .SelectMany(c => c.Orders);

SelectMany()允许您以一种需要第二个Select()或循环的方式折叠多维序列。

更多细节请参见这篇博客文章。


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。net Fiddle


SelectMany有几个重载。其中之一允许您在遍历层次结构时跟踪父节点和子节点之间的任何关系。

示例:假设您有以下结构:League -> Teams -> Player。

您可以很容易地返回一个平坦的播放器集合。但是你可能会失去任何关于玩家所在团队的信息。

幸运的是,有一个重载用于此目的:

var teamsAndTheirLeagues = 
         from helper in leagues.SelectMany
               ( l => l.Teams
                 , ( league, team ) => new { league, team } )
                      where helper.team.Players.Count > 2 
                           && helper.league.Teams.Count < 10
                           select new 
                                  { LeagueID = helper.league.ID
                                    , Team = helper.team 
                                   };

前面的例子来自Dan的IK博客。我强烈建议你看一看。


Select是一个简单的从源元素到结果元素的一对一投影。选择- - - 当查询表达式中有多个from子句时使用Many:原始序列中的每个元素都用于生成一个新序列。


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<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);
}

De Gea 阿尔芭 科斯塔 别墅 Busquets

...


Some SelectMany可能不需要。以下2个查询给出相同的结果。

Customers.Where(c=>c.Name=="Tom").SelectMany(c=>c.Orders)

Orders.Where(o=>o.Customer.Name=="Tom")

对于一对多关系,

如果从“1”开始,则需要SelectMany,它将平展many。 如果从“Many”开始,则不需要SelectMany。(仍然能够从“1”中过滤,这也比以下标准的连接查询更简单)


from o in Orders
join c in Customers on o.CustomerID equals c.ID
where c.Name == "Tom"
select o

我认为这是理解的最好方式。

            var query =
            Enumerable
                .Range(1, 10)
                .SelectMany(ints => Enumerable.Range(1, 10), (a, b) => $"{a} * {b} = {a * b}")
                .ToArray();

        Console.WriteLine(string.Join(Environment.NewLine, query));

        Console.Read();

乘法表的例子。


没有太多的技术-数据库与许多组织,每个有许多用户:-

var orgId = "123456789";

var userList1 = db.Organizations
                   .Where(a => a.OrganizationId == orgId)
                   .SelectMany(a => a.Users)
                   .ToList();

var userList2 = db.Users
                   .Where(a => a.OrganizationId == orgId)
                   .ToList();

都为所选组织返回相同的ApplicationUser列表。

第一个“项目”从Organization到Users,第二个直接查询Users表。


当查询返回一个字符串(一个char数组)时更清楚:

例如,如果列表" Fruits "包含" apple "

'Select'返回字符串:

Fruits.Select(s=>s) 

[0]: "apple"

'SelectMany'将字符串平展:

Fruits.SelectMany(s=>s)

[0]: 97  'a'
[1]: 112 'p'
[2]: 112 'p'
[3]: 108 'l'
[4]: 101 'e'

只是为了另一种观点,可能会帮助一些函数式程序员:

选择是映射 SelectMany是绑定的(或flatMap的Scala/Kotlin人)


再举一个如何使用SelectMany + Select来累积子数组对象数据的例子。

假设我们有一些带着手机的用户:

class Phone { 
    public string BasePart = "555-xxx-xxx"; 
}

class User { 
    public string Name = "Xxxxx";
    public List<Phone> Phones; 
}

现在我们需要选择所有用户的所有手机的basepart:

var usersArray = new List<User>(); // array of arrays
List<string> allBaseParts = usersArray.SelectMany(ua => ua.Phones).Select(p => p.BasePart).ToList();

下面是一个用于测试的初始化小集合的代码示例:

class Program
{
    static void Main(string[] args)
    {
        List<Order> orders = new List<Order>
        {
            new Order
            {
                OrderID = "orderID1",
                OrderLines = new List<OrderLine>
                {
                    new OrderLine
                    {
                        ProductSKU = "SKU1",
                        Quantity = 1
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU2",
                        Quantity = 2
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU3",
                        Quantity = 3
                    }
                }
            },
            new Order
            {
                OrderID = "orderID2",
                OrderLines = new List<OrderLine>
                {
                    new OrderLine
                    {
                        ProductSKU = "SKU4",
                        Quantity = 4
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU5",
                        Quantity = 5
                    }
                }
            }
        };

        //required result is the list of all SKUs in orders
        List<string> allSKUs = new List<string>();

        //With Select case 2 foreach loops are required
        var flattenedOrdersLinesSelectCase = orders.Select(o => o.OrderLines);
        foreach (var flattenedOrderLine in flattenedOrdersLinesSelectCase)
        {
            foreach (OrderLine orderLine in flattenedOrderLine)
            {
                allSKUs.Add(orderLine.ProductSKU);
            }
        }

        //With SelectMany case only one foreach loop is required
        allSKUs = new List<string>();
        var flattenedOrdersLinesSelectManyCase = orders.SelectMany(o => o.OrderLines);
        foreach (var flattenedOrderLine in flattenedOrdersLinesSelectManyCase)
        {
            allSKUs.Add(flattenedOrderLine.ProductSKU);
        }

       //If the required result is flattened list which has OrderID, ProductSKU and Quantity,
       //SelectMany with selector is very helpful to get the required result
       //and allows avoiding own For loops what according to my experience do code faster when
       // hundreds of thousands of data rows must be operated
        List<OrderLineForReport> ordersLinesForReport = (List<OrderLineForReport>)orders.SelectMany(o => o.OrderLines,
            (o, ol) => new OrderLineForReport
            {
                OrderID = o.OrderID,
                ProductSKU = ol.ProductSKU,
                Quantity = ol.Quantity
            }).ToList();
    }
}
class Order
{
    public string OrderID { get; set; }
    public List<OrderLine> OrderLines { get; set; }
}
class OrderLine
{
    public string ProductSKU { get; set; }
    public int Quantity { get; set; }
}
class OrderLineForReport
{
    public string OrderID { get; set; }
    public string ProductSKU { get; set; }
    public int Quantity { get; set; }
}

想想这个例子:

        var array = new string[2]
        {
            "I like what I like",
            "I like what you like"
        };
        //query1 returns two elements sth like this:
        //fisrt element would be array[5]  :[0] = "I" "like" "what" "I" "like"
        //second element would be array[5] :[1] = "I" "like" "what" "you" "like"
        IEnumerable<string[]> query1 = array.Select(s => s.Split(' ')).Distinct();

        //query2 return back flat result sth like this :
        // "I" "like" "what" "you"
        IEnumerable<string> query2 = array.SelectMany(s => s.Split(' ')).Distinct();

因此,正如你所看到的,像“I”或“like”这样的重复值已从query2中删除,因为“SelectMany”将在多个序列上平坦和投影。 但是query1返回字符串数组序列。由于query1中有两个不同的数组(第一个和第二个元素),因此不会删除任何东西。


SelectMany方法将IEnumerable<IEnumerable<T>>分解为IEnumerable<T>,就像共产主义一样,每个元素都以相同的方式表现(愚蠢的家伙拥有与天才相同的权利)。

var words = new [] { "a,b,c", "d,e", "f" };
var splitAndCombine = words.SelectMany(x => x.Split(','));
// returns { "a", "b", "c", "d", "e", "f" }

SelectMany()方法用于抚平序列,其中序列的每个元素都是独立的。

我的类用户是这样的

class User
    {
        public string UserName { get; set; }
        public List<string> Roles { get; set; }
    }

主要:

var users = new List<User>
            {
                new User { UserName = "Reza" , Roles = new List<string>{"Superadmin" } },
                new User { UserName = "Amin" , Roles = new List<string>{"Guest","Reseption" } },
                new User { UserName = "Nima" , Roles = new List<string>{"Nurse","Guest" } },
            };

var query = users.SelectMany(user => user.Roles, (user, role) => new { user.UserName, role });

foreach (var obj in query)
{
    Console.WriteLine(obj);
}
//output

//{ UserName = Reza, role = Superadmin }
//{ UserName = Amin, role = Guest }
//{ UserName = Amin, role = Reseption }
//{ UserName = Nima, role = Nurse }
//{ UserName = Nima, role = Guest }

您可以对序列的任何项使用操作

int[][] numbers = {
                new[] {1, 2, 3},
                new[] {4},
                new[] {5, 6 , 6 , 2 , 7, 8},
                new[] {12, 14}
            };

IEnumerable<int> result = numbers
                .SelectMany(array => array.Distinct())
                .OrderBy(x => x);

//output

//{ 1, 2 , 2 , 3, 4, 5, 6, 7, 8, 12, 14 }
 List<List<int>> numbers = new List<List<int>> {
                new List<int> {1, 2, 3},
                new List<int> {12},
                new List<int> {5, 6, 5, 7},
                new List<int> {10, 10, 10, 12}
            };

 IEnumerable<int> result = numbers
                .SelectMany(list => list)
                .Distinct()
                .OrderBy(x=>x);

//output

// { 1, 2, 3, 5, 6, 7, 10, 12 }

SelectMany()的正式描述是:

将序列的每个元素投射到IEnumerable上并展开 产生的序列变成一个序列。

SelectMany()将结果序列平铺成一个序列,并对其中的每个元素调用结果选择器函数。

class PetOwner
{
    public string Name { get; set; }
    public List<String> Pets { get; set; }
}

public static void SelectManyEx()
{
     PetOwner[] petOwners =
         { new PetOwner { Name="Higa, Sidney",
              Pets = new List<string>{ "Scruffy", "Sam" } },
           new PetOwner { Name="Ashkenazi, Ronen",
              Pets = new List<string>{ "Walker", "Sugar" } },
           new PetOwner { Name="Price, Vernette",
              Pets = new List<string>{ "Scratches", "Diesel" } } };

// Query using SelectMany().
IEnumerable<string> query1 = petOwners.SelectMany(petOwner => petOwner.Pets);

Console.WriteLine("Using SelectMany():");

// Only one foreach loop is required to iterate
// through the results since it is a
// one-dimensional collection.
foreach (string pet in query1)
{
    Console.WriteLine(pet);
}

// This code shows how to use Select()
// instead of SelectMany().
IEnumerable<List<String>> query2 =
    petOwners.Select(petOwner => petOwner.Pets);

Console.WriteLine("\nUsing Select():");

// Notice that two foreach loops are required to
// iterate through the results
// because the query returns a collection of arrays.
foreach (List<String> petList in query2)
{
    foreach (string pet in petList)
    {
        Console.WriteLine(pet);
    }
    Console.WriteLine();
}
}

/*
   This code produces the following output:

    Using SelectMany():
    Scruffy
    Sam
    Walker
    Sugar
    Scratches
    Diesel

   Using Select():
   Scruffy
   Sam

   Walker
   Sugar

   Scratches
   Diesel
  */

主要的区别是每个方法的结果,而SelectMany()返回一个扁平的结果;Select()返回一个列表的列表,而不是一个扁平的结果集。

因此,SelectMany的结果是一个列表

{斯库菲,山姆,沃克,甜甜,划痕,迪塞尔}

你可以迭代每一项。但是对于select的结果,您需要一个额外的foreach循环来遍历结果,因为查询返回一个数组集合。


假设你有一组国家

var countries = new[] { "France", "Italy" };

如果你对国家执行Select,你将得到数组中的每个元素IEnumerable<T>

IEnumerable<string> selectQuery = countries.Select(country => country);

在上面的代码中,国家表示指向数组中每个国家的字符串。现在迭代selectQuery以获得国家:

foreach(var country in selectQuery)
    Console.WriteLine(country);

// output
//
// France
// Italy

如果你想打印每个国家的字符,你必须使用嵌套foreach

foreach (var country in selectQuery)
{
    foreach (var charOfCountry in country)
    {
        Console.Write(charOfCountry + ", ");
    }
}

// output

// F, r, a, n, c, e, I, t, a, l, y,

好的。现在尝试对国家执行SelectMany。这一次SelectMany获取每个国家作为字符串(和以前一样),因为字符串类型是一个字符的集合,SelectMany尝试将每个国家分为它的组成部分(字符),然后返回一个字符的集合IEnumerable<T>

IEnumerable<char> selectManyQuery = countries.SelectMany(country => country);

在上面的代码中,country表示一个字符串,该字符串引用数组中的每个国家,但返回值是每个国家的字符

实际上SelectMany喜欢在集合中获取两层,并将第二层平铺为IEnumerable<T>

现在遍历selectManyQuery以获得每个国家的字符:

foreach(var charOfCountry in selectManyQuery)
    Console.Write(charOfCountry + ", ");

// output

// F, r, a, n, c, e, I, t, a, l, y,

select操作符用于从集合中选择值,SelectMany操作符用于从集合的集合(即嵌套集合)中选择值。