我正在尝试创建一个计算所有订单的表,并将它们分组到从sql到linq的表中,以便在带有谷歌图表的条形图中使用。
Table`
Orders Status
8 Created
3 Delayed
4 Enroute
SQL
SELECT Count (OrderID) as 'Orders', order_status FROM [ORDER]
where order_status ='Created'OR order_status= 'Delayed' OR order_status='Enroute'
group by order_status
控制器
public ActionResult GetChart()
{
var Orders = db.Order.Select(a => new { a.OrderID, a.order_status })
.GroupBy(a => a.order_status);
return Json(Orders, JsonRequestBehavior.AllowGet);
}
这并没有显示正确的结果,因为linq似乎是错误的。 有人可以指出我正确的方向吗?我对此比较陌生。 提前谢谢。
答案 0 :(得分:0)
这应该有效: -
var result = db.Order.Where(x => x.order_status == "Created"
|| x.order_status == "Delayed"
|| x.order_status == "Enroute")
.GroupBy(x => x.order_status)
.Select(x => new
{
order_status = x.Key,
Orders = x.Count()
});
或者,如果您更喜欢查询语法,那么: -
var result = from o in db.Order
where o.order_status == "Created" || o.order_status == "Delayed"
|| o.order_status == "Enroute"
group o by o.order_status
select new
{
orderStatus = x.Key,
Counts = x.Count()
};
答案 1 :(得分:0)
我认为您希望按Status
进行分组并计算每个组中的订单总数(我构建了一个简单的控制台程序来演示)。我想数据是:
Orders Status
8 Created
3 Delayed
4 Enroute
2 Created
1 Delayed
<强> Order.cs 强>
public class Order
{
public Order(int orderId, string status)
{
OrderId = orderId;
Status = status;
}
public int OrderId { get; set; }
public string Status { get; set; }
}
<强> Program.cs的强>
class Program
{
static void Main(string[] args)
{
// Data
var orders = new List<Order>
{
new Order(8, "Created"),
new Order(3, "Delayed"),
new Order(4, "Enroute"),
new Order(2, "Created"),
new Order(1, "Delayed"),
};
// Query
var query = orders
.GroupBy(x => x.Status)
.Select(x => new {Status = x.Key, Total = x.Count()});
// Display
foreach (var item in query)
{
Console.WriteLine(item.Status + ": " + item.Total);
}
Console.ReadLine();
}
}
您需要关注的是query
。使用GroupBy
后,您将获得一个组列表。对于每个组,Key
是要分组的条件(此处为Status
)。然后,我们调用Count()
来获取该组中元素的总数。
因此,从上面的程序中,输出应为:
Created: 2
Delayed: 2
Enroute: 1