【问题标题】:SelectMany in Linq to entityLinq中的SelectMany到实体
【发布时间】:2010-05-18 16:35:04
【问题描述】:

我在 microsoft 网站上查看了一些关于 linq 的示例,我看到了一个需要修改的示例!

http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx#SelectManyCompoundfrom3

public void Linq16()
{
List<Customer> customers = GetCustomerList();

var orders =
    from c in customers
    from o in c.Orders
    where o.OrderDate >= new DateTime(1998, 1, 1)
    select new { c.CustomerID, o.OrderID, o.OrderDate };

ObjectDumper.Write(orders);
}

选择检索 CustomerID、OrderID 和 OrderDate 我想选择 CustomerID 和包含该用户所有订单的 System.Collection.Generic.List&lt;int&gt;!本质上,我想按 CustomerID 对订单进行分组,但我注意到 linq to entity 不允许在选择中使用 .ToList(object)

我想要这样的东西......

List<Customer> customers = GetCustomerList();

var orders =
    from c in customers
    from o in c.Orders
    where o.OrderDate >= new DateTime(1998, 1, 1)
    select new xpto
    {
      TheCostumerID = c.CustomerID, 
      CostumerOrders = o.Select(i=>i.OrderID).ToList(),
    };

...但是 .ToList() 是个大问题,至少对我来说是这样。

【问题讨论】:

  • “ToList”有什么问题?
  • .ToList() 在 linq to entity 的选择中似乎不起作用!

标签: linq linq-to-entities


【解决方案1】:

你有机会按子句分组吗?

 from orders in context.Orders
 group orders by orders.CustomerID into ordersGroup
 select new { CustomerID = ordersGroup.Key, 
              Orders = ordersGroup };

如果不是您要找的,请告诉我。

【讨论】:

    【解决方案2】:

    我发现功能性更强的语法更简洁,但我会像这样使用 GroupBy:

    DateTime minDate = new DateTime(1998, 1, 1);
    
    ordersEntities = entities.Customers.GroupJoin(entities.Orders, // Table to join with
        customer => customer.Id, order => order.CustomerId, // Properties to match on
        (customer, orders) => new {
            Customer = customer,
            Orders = orders.Where(o => o.Date > minDate)
        });
    

    然后使用 ToList() 弹出 LINQ-to-entities 并进入 LINQ-to-objects(当然要注意这对进入数据库的实际 SQL 查询有何影响):

    return ordersEntities.ToList()
        .Select(oe => new {
            Customer = oe.Customer,
            Orders = oe.ToList()
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      相关资源
      最近更新 更多