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

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


当前回答

当查询返回一个字符串(一个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工作起来像一个连接快捷方式。

所以你可以:

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

再举一个如何使用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; }
}

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 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,