简体   繁体   中英

Group By object within a nested list linq

What i am trying to do is i have sales order object which contains

sales order header
and list of order lines

within the order lines i have the actual order line, product information object and stock information object:

public class SalesOrder
{
  public Header SalesHeader { get; set; }
  public List<OrderLineProductInfo> OrderLines { get; set; }
}

public class OrderLineProductInfo
{
  public Line salesOrderLine { get; set; }
  public Info ProductInfo { get; set; }
  public Stock ProductStock { get; set; }
}

so i can get a list of SalesOrder Objects so example sales order index 0

has 2 lines the ProductStockObject within one of these lines has Preferred Supplier of abc and the other line has Preferred Supplier 123

i want to be able to group on the Preferred Supplier property

var separatePreferredSuppliers =
     (from b in x.OrderLines
                 .GroupBy(g => g.ProductStock.PreferredSupplier ) 
                   select ...
     ).ToList();

not quite sure what comes next what needs to be selected? a new list of SalesOrder?

I want it so that it gives two instances of the sales order but split in 2 one for each preferred supplier

I think I get what you mean

from line in x.OrderLines
group line by line.ProductStock.PreferredSupplier into grouped
select new SalesOrder
{
     OrderLines = grouped.ToList()
}

though I'm not sure how you populate your SalesHeader

当你知道groupby函数是什么时候很容易 - 你想要密钥和列表:

.Select( (g) => new { supplier = g.Key, prodlist = g.ToList()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM