linq - 获取最新的相关记录

时间:2011-11-15 10:26:03

标签: c# linq linq-to-sql

假设我有CustomerOrder个对象,其中一个Customer可以有多个Orders(因此Order类有一个CustomerId我希望返回所有CustomerAndMostRecentOrder个对象的集合,其定义如下:

public class CustomerAndMostRecentOrder
{
  public Customer Customer { get; set; }
  public Order MostRecentOrder { get; set; }
}

我如何编写执行此操作的Linq查询(我正在使用Linq to SQL)?

4 个答案:

答案 0 :(得分:2)

您可以使用以下查询:

from c in customers
select new CustomerAndMostRecentOrder
    {
        Customer = c,
        MostRecentOrder = c.Orders.OrderByDescending(o => o.PurchaseDate).FirstOrDefault()
    };

这将使用客户的导航属性进行订购。 MostRecentOrder是通过在某些DateTime属性上对Orders进行排序然后加载第一个来获得的。

答案 1 :(得分:1)

您需要在CreatedDate表格中设置Order日期才能获得最新订单。然后,要获取CustomerAndMostRecentOrder对象,请执行以下查询:

from c in customers
join o in orders on c.ID equals o.CustomerID into co
select new CustomerAndMostRecentOrder
{
    Customer = c,
    MostRecentOrder = co.OrderByDescending(o => o.CreatedDate).FirstOrDefault()
}

答案 2 :(得分:1)

public class CustomerAndMostRecentOrder
{
    public CustomerAndMostRecentOrder(Customer customer, Order mostRecentOrder)
    {
        Customer = customer;
        MostRecentOrder = mostRecentOrder;
    }

    public Customer Customer { get; set; }
    public Order MostRecentOrder { get; set; }
}

public class Order
{
}


public class Customer
{
    public IEnumerable<Order> GetOrders()
    {

    }
}


public static class UsageClass
{

    public static void Sample(IEnumerable<Customer> allCustomers)
    {
        IEnumerable<CustomerAndMostRecentOrder> customerAndMostRecentOrders =
            allCustomers.Select(customer => new CustomerAndMostRecentOrder(customer, customer.GetOrders().Last()));
    }

}

答案 3 :(得分:0)

作为另一种选择,您可能需要查看http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.associatewith.aspx中讨论的DataLoadOptions.AssociateWith。只需根据上下文设置您的要求,您就不必担心在查询级别过滤子项。