Linq to objects,加入集合并简化select new

时间:2014-01-27 10:26:40

标签: linq linq-to-objects

我需要一些帮助来简化linq查询。我有2个班级发票和客户。 发票有一个属性CustomerId和一个属性Customer。 我需要获取所有发票并包含Customer对象。 我不喜欢我的查询,因为如果将新属性添加到Invoice对象,它需要更改。 我不能在这个阶段之前加入发票和客户,因此不能替代。

我的查询。

var customers = GetCustomers();
var invoices = GetInvoices();
var joinedList = (from x in invoices
                  join y in customers on x.CustomerId equals y.CustomerId
                  select new Invoice
                  {
                     Amount = x.Amount,
                     CustomerId = x.CustomerId,
                     Customer = y,
                     InvoiceId = x.InvoiceId
                   }).ToList();

课程

   public class Invoice
   {
      public int InvoiceId { get; set; }
      public double Amount { get; set; }
      public int CustomerId { get; set; }
      public Customer Customer { get; set; }
   }

   public class Customer
   {
      public int CustomerId { get; set; }
      public string Name { get; set; }
   }
   private static IEnumerable<Invoice> GetInvoices()
   {
         yield return new Invoice
         {
            Amount = 34,
            CustomerId = 1,
            InvoiceId = 1
         };
         yield return new Invoice
         {
            Amount = 44.7,
            CustomerId = 1,
            InvoiceId = 2
         };
         yield return new Invoice
         {
            Amount = 67,
            CustomerId = 2,
            InvoiceId = 3
         };
         yield return new Invoice
         {
            Amount = 89,
            CustomerId = 3,
            InvoiceId = 4
         };
      }

      private static IEnumerable<Customer> GetCustomers()
      {
         yield return new Customer
         {
            CustomerId = 1,
            Name = "Bob"
         };
         yield return new Customer
         {
            CustomerId = 2,
            Name = "Don"
         };
         yield return new Customer
         {
            CustomerId = 3,
            Name = "Alice"
         };
      }

1 个答案:

答案 0 :(得分:1)

为什么不只是一个简单的foreach循环:

// Dictionary for efficient look-up
var customers = GetCustomers().ToDictionary(c => c.CustomerId);
var invoices = GetInvoices().ToList();

//TODO: error checking
foreach(var i in invoices)
    i.Customer = customers[i.CustomerId];