正确组织和转换对象

我有一个复杂的SQL查询,返回的表是这样的:

enter image description here

I have it described by this object - IEnumerable<Invoice> where:

public partial class Invoice
{
    public string DocumentNumber { get; set; }
    public DateTime? DocumentDate { get; set; }
    public string DocumentReference { get; set; }
    public string SerialNumber { get; set; }
    public string ProductCode { get; set; }
    public string Description { get; set; }
    public string Certificate { get; set; }
}

这些对象集的独特之处在于,它们按前三个字段分组(如果它们相同),其余字段则不同。

我的任务是实现此数据的分层表示,其外观应如下所示:

enter image description here

I decided for myself that my final view-object should have the following structure - Dictionary<InvoiceHeader, List<InvoiceHierarchi>> where:

public class InvoiceHeader
{
   public string DocumentNumber { get; set; }
   public DateTime? DocumentDate { get; set; }
   public string DocumentReference { get; set; }
}

public class InvoiceHierarchi
{
   public string SerialNumber { get; set; }
   public string ProductCode { get; set; }
   public string Description { get; set; }
   public string Certificate { get; set; }
}

Question #1: Can I write LINQ query that converts IEnumerable<Invoice> to Dictionary<InvoiceHeader, List<InvoiceHierarchi>> and how to do it right?

问题2:总的来说,我是否选择了正确的方法来解决任务?

评论
  • uqui
    uqui 回复

    Can I write LINQ query that converts IEnumerable<Invoice> to Dictionary<InvoiceHeader, List<InvoiceHierarchi>> and how to do it right?

    Yes, you can. Try something like that, group invoices by InvoiceHeader and convert the result using ToDictionary method

    var invoices = new List<Invoice>();
    var result = invoices.GroupBy(i => new InvoiceHeader
    {
        DocumentDate = i.DocumentDate,
        DocumentNumber = i.DocumentNumber,
        DocumentReference = i.DocumentReference
    }).ToDictionary(g => g.Key, g => g.Select(i => new InvoiceHierarchi
    {
        Certificate = i.Certificate,
        SerialNumber = i.SerialNumber,
        ProductCode = i.ProductCode,
        Description = i.Description
    }).ToList());