每张发票显示唯一产品的字符串/整数数组 [英] Per Invoice show string/int array of unique products

查看:106
本文介绍了每张发票显示唯一产品的字符串/整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张发票清单和每张发票上的所有产品. 每个发票可以有多个相同的产品

I have a list of Invoices and all the Products on each Invoice. Each Invoice can have multiples of the same product

class InvoiceProducts 
{
    public int InvoiceID { get; set; }
    public int ProductID { get; set; }
}


var list = new List<InvoiceProducts>();
list.Add(new { InvoiceID = 7000, ProductID=15});
list.Add(new { InvoiceID = 7000, ProductID=10});
list.Add(new { InvoiceID = 7000, ProductID=10});
list.Add(new { InvoiceID = 7000, ProductID=15});

list.Add(new { InvoiceID = 7010, ProductID=12});
list.Add(new { InvoiceID = 7010, ProductID=20});
list.Add(new { InvoiceID = 7010, ProductID=12});

list.Add(new { InvoiceID = 7021, ProductID=1});
list.Add(new { InvoiceID = 7021, ProductID=1});

我可以请协助吗 按InvoiceID分组,并具有(唯一的产品的)(排序的)整数列表 每张发票 (排序的原因是,我以后需要将其与其他具有相同产品的发票进行匹配)

Can I please ask assistance in grouping per InvoiceID, and having a (Sorted) integer list of unique Products per invoice (The reason for sorting is that I need to match this with other invoices with the same products later)

InvoiceID   ProductID
7000        10,15       
7010        12,20
7021        1

尝试失败:

  var tl2 = List
      .GroupBy(x => x.InvoiceID)
      .ToDictionary(y => y.Key, y => y.Distinct().ToList());

尝试失败的原因:它有一个按InvoiceID正确分组的字典,但是Invoice 7000有4个订单项,而不是2个唯一产品

Failed Attempt explained : it has a dictionary which grouped correctly by InvoiceID, but invoice 7000 had 4 line items instead of 2 unique products

推荐答案

您要

You want ToLookup here - it's designed for precisely this scenario.

var lookup = list.ToLookup(x => x.InvoiceID, x => x.ProductID);

该ID仍将包含重复的产品ID,但是在获取它们时,您可以轻松地使它们与众不同:

That will still contain the duplicate product IDs, but you can easily make them distinct when you fetch them:

var products = list[7000].Distinct();

或者您也可以在列表中使用Distinct():

Or you could just use Distinct() on your list:

var lookup = list.Distinct()
                 .ToLookup(x => x.InvoiceID, x => x.ProductID);

这将与使用匿名类型的代码一起使用,但是如果您实际使用InvoiceProducts类型,则不是.您可以随时进行投影:

That would work with the code using the anonymous type, but not if you actually use your InvoiceProducts type. You could always project:

var lookup = list.Select(x => new { x.InvoiceID, x.ProductID })
                 .Distinct()
                 .ToLookup(x => x.InvoiceID, x => x.ProductID);

...或者只是使您的InvoiceProducts类型适当地实现相等性.

... or just make your InvoiceProducts type implement equality appropriately.

这篇关于每张发票显示唯一产品的字符串/整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆