How to get unique product records in List <Order> with LINQ

I have a classic Order → Order Row script something like this:

public class Order 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int Amount { get; set; }
}

and the list <Order>. From this list of orders I want to get a list of all unique ProductIds.

I solved it like this:

var orders = new List<Order>();
// TODO get the orders from DB
var products = new Dictionary<int,int>();
orders.ForEach(order => order.OrderRows.ForEach(row => products[row.ProductId]=row.ProductId));

but I had questions about my use of the dictionary and why I did not use LINQs GroupBy, as well as comments, which was not entirely clear how this works. I think the solution is fine, but the comments made me try to solve it in LINQ, but for some reason I hit a brick wall.

How can I get a list of unique product identifiers from an order list with LINQ here?

+3
source share
3 answers

, :

var products = orders.SelectMany(o => o.OrderRows)
                     .Select(r => r.ProductId)
                     .Distinct();
+7

SelectMany, - , :

var productIDs =
(
  from order in orders
  from orderrow in order.OrderRows
  select orderrow.ProductId
).Distinct();
+2

This should get unique product identifiers from the order list.

var orders = new List<Order>();

// Get orders from database.

IEnumerable<int> uniqueIds = orders.SelectMany(order => order.OrderRows)
    .Select(row => row.ProductId).Distinct();
+1
source

Source: https://habr.com/ru/post/1724837/


All Articles