按深层次类/实体的字段使用linq按集合排序

时间:2017-03-16 12:30:14

标签: c# linq

我有以下实体结构。我有几个装饰器将填充Invoice.InvoiceLines,最后我想通过OrderReference订购那些invoicelines

 public class Invoice 
    {
        private readonly IList<InvoiceLine> _invoiceLines;
        public virtual IList<InvoiceLine> InvoiceLines => _invoiceLines;

        public Invoice()
        {
            _invoiceLines = new List<InvoiceLine>();
        }

    }

    public class InvoiceLine 
    {

        private readonly IList<TransactionLine> _transactionLines = new List<TransactionLine>();
        public virtual IReadOnlyCollection<TransactionLine> TransactionLines => new ReadOnlyCollection<TransactionLine>(_transactionLines);

        public virtual void AddTransactionLine(TransactionLine transactionLine)
        {
            transactionLine.ThrowIfNull(nameof(transactionLine), "can't be null");
            _transactionLines.Add(transactionLine);
        }
    }


    public class PermanentPlacementTransactionLine : TransactionLine
    {

        public PermanentPlacement PermanentPlacement { get; set; }
    }


      public  class PermanentPlacement 
    {
        public virtual string JobReference { get; set; }
        public virtual string OrderReference { get; set; }
    }

我想要做的是通过OrderReference订购发票行。

  foreach (var invoice in DecoratedResult.Invoices.Where(inv => inv.InvoiceType == InvoiceType.Weekly))
            {
                var customer = CustomerRepository.FetchByAccountNumber(invoice.CustomerAccountNumber);
                if (customer.InvoiceProperties.InvoiceSequence == InvoiceSequence.OrderReference)
                {
                   // order by fields at deep level.
                   // invoice.InvoiceLines.OrderBy(i => i.TransactionLines.OfType<PermanentPlacementTransactionLine>());
                }
            }

我可以将属性暴露给invoiceline然后相应地设置但是我有什么方法可以使用linq来做。

1 个答案:

答案 0 :(得分:0)

我设法按照以下方式行事

     invoiceLines.OrderBy(Func1)
     //.ThenBy(Func2).
     //ThenBy(Func3).
     ToList();

private static string Func1(InvoiceLine invoiceLine) =>
            invoiceLine.TransactionLines.OfType<PermanentPlacementTransactionLine >().First()
                .OrderReference ;