我有以下两个POCO的
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,Count,(作为控制器操作的Json),所以我创建了一个新的POCO来保存结果。如下所示:
public class MostActive
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Count { get; set; }
}
虽然它不起作用,但这是我目前的尝试到目前为止:
var results = (from c in Customers
from o in Orders
where c.Id == o.CustomerId
orderby c.Id.Count descending
select new MostActive
{
FirstName = c.FirstName,
LastName = c.LastName,
Id = c.Id,
Count = h.Id.Count
}).Take(10);
答案 0 :(得分:3)
这涉及几个步骤,你可以这样分解:
这样的事情应该这样做:
<div id="container">
<section id="1"></section>
<section id="2"></section>
<section id="3"></section>
</div>
<div id="nav">
<a href="#1">link</a>
<a href="#2">link</a>
<a href="#3">link</a>
</div>
或者继续你从哪里开始,这几乎就在那里,这也将起作用。正如您所说,主要部分是添加分组,然后对客户进行连接:
var results = Orders
.GroupBy(o => o.CustomerId)
.OrderByDescending(og => og.Count())
.Take(10)
.Select(og => new {
Customer = Customers.Single(c => c.Id.Equals(og.Key)),
Orders = og
})
.Select(c => new MostActive {
Id = c.Customer.Id,
FirstName = c.Customer.FirstName,
LastName = c.Customer.LastName,
Count = c.Orders.Count()
});
答案 1 :(得分:1)
正确定义外键后,这应该很容易
Customers.Select(c => new MostActive {
FirstName = c.FirstName,
LastName = c.LastName,
Id = c.Id,
Count = c.Orders.Count()
})
.OrderByDescending(o => o.Count)
.Take(10);
外键在数据库中定义。在linq下我假设Linq2SQL或EF,它们都自动从数据库生成这些关系。