SelectMany in Linq for an object

I have looked at some examples on the microsoft site about linq and I see an example that I need to change!

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

      

If you have a selection that returns a CustomerID, OrderID, and OrderDate, I want to select a CustomerID and System.Collection.Generic.List<int>

that contains all orders for that user! Basically, I want to group my orders by CustomerID, but I noticed that linq for entity doesn't allow .ToList(object)

inside selection.

I want something like this ...

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

      

... but .ToList () is a big problem, at least for me.

I'm trying to find a solution for this, but I haven't followed through with anything so far!

Please help me.

+2


a source to share


3 answers


Have you had the opportunity to group by reservation?

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

      



Let me know if this is not what you were looking for.

0


a source


Try:



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

0


a source


I found the more functional syntax to be more concise, but I would use GroupBy like this:

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

      

And then using ToList () to pop out of LINQ-to-entity and into LINQ-to-objects (considering how this affects the actual SQL queries coming into your database, of course):

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

      

0


a source







All Articles