【问题标题】:Per Invoice show string/int array of unique products每张发票显示唯一产品的字符串/整数数组
【发布时间】:2015-09-29 12:56:04
【问题描述】:

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

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 分组,并具有唯一产品的(排序的)整数列表 每张发票 (排序的原因是我以后需要把这个和其他相同产品的发票匹配)

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 正确分组的字典,但发票 7000 有 4 个行项目而不是 2 个唯一产品

【问题讨论】:

    标签: c# linq unique linq-group


    【解决方案1】:

    你想在这里ToLookup - 它正是为这种情况而设计的。

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

    这仍将包含重复的产品 ID,但您可以在获取它们时轻松区分它们:

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

    或者你可以在你的列表中使用Distinct()

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

    这适用于使用匿名类型的代码,但如果您实际使用 InvoiceProducts 类型,则。你总是可以投射:

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

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

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      相关资源
      最近更新 更多