我有以下两个POCO&#39>
public class Customers
{
public Guid Id { get; set; }
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
和
public class Orders
{
public Guid Id { get; set; }
public Guid CustomerId { get; set; }
public string Product { get; set; }
public DateTime Date { get; set; }
}
假设我的数据服务返回一个List< Customers>和列表<订单>,我如何使用Linq获取每个客户的最后一个订单的日期?
我想返回Customer.Id,Customer.FirstName,Customer.LastName,Order.Id,Order.Date和Order.Product(作为控制器操作中的Json),因此我还需要创建一个新的POCO保持结果?如下所示:
public class CustomerOrders
{
public Guid CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid OrderId { get; set; }
public DateTime Date { get; set; }
public string Product { get; set; }
}
答案 0 :(得分:0)
您可能希望使用GROUP BY
和JOIN
,如下所示:
var customerOrders =
(from c in customers
join o in (from o1 in orders
group o1 by o1.CustomerId into og
select new { CustomerId = og.Key, Latest = og.Max(d => d.Date) })
on c.Id equals o.CustomerId
join o2 in orders
on new {CustmerId = o.CustomerId, Date = o.Latest }
equals new { CustmerId = o2.CustomerId, Date = o2.Date }
select new CustomerOrders
{
CustomerId = c.Id,
FirstName = c.FirstName,
LastName = c.LastName,
OrderId = o2.Id,
Date = o.Latest,
Product = o2.Product
});
如果您希望客户的结果没有任何订单,请使用LEFT OUTER JOIN
并使用DefaultIfEmpty
这样的人:
var customerOrders =
(from c in customers
join o in (from o1 in orders
group o1 by o1.CustomerId into og
select new { CustomerId = og.Key, Latest = og.Max(d => d.Date) })
on c.Id equals o.CustomerId into co
from o in co.DefaultIfEmpty() // LEFT OUTER JOIN 1
join o2 in orders
on new { CustmerId = (o == null)? Guid.Empty : o.CustomerId, Date = (o == null)? DateTime.MinValue : o.Latest }
equals new { CustmerId = o2.CustomerId, Date = o2.Date } into oo
from o2 in oo.DefaultIfEmpty() // LEFT OUTER JOIN 2
select new CustomerOrders
{
CustomerId = c.Id,
FirstName = c.FirstName,
LastName = c.LastName,
OrderId = (o2 == null)? Guid.Empty : o2.Id,
Date = (o == null)? DateTime.MinValue : o.Latest,
Product = (o == null)? null : o2.Product
});
请注意LEFT OUTER JOIN
可以加入null值,因此您必须在linq查询中添加空检查。