English 中文(简体)
How to get unique entries of products in a List<Order> with LINQ
原标题:

I have a classic Order -> Order Row scenario 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 a List<Order>. From that list of orders I want to get a list of all the 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 got questions about my use of Dictionary and why I didn t use LINQs GroupBy and also comments that it wasn t very clear how it worked. I think the solution is fine but the comments made me want to try to solve it in LINQ but for some reason I hit a brick wall trying.

How do I get a list of unique products ids from a list of orders with LINQ here?

最佳回答

Untested, but how about:

var products = orders.SelectMany(o => o.OrderRows)
                     .Select(r => r.ProductId)
                     .Distinct();
问题回答

If you don t want to remember SelectMany, this query comprehension syntax will still get you where you want to go:

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

This should get the unique product ids from the list of orders.

var orders = new List<Order>();

// Get orders from database.

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签