[c#]完全外部联接和计数

发布时间: 2017/2/26 16:16:20
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我试着重新创建 LINQ 返回 JSON 下面的 SQL 查询︰

SELECT a.Title, COUNT(b.ActionID) FROM labels a
FULL JOIN [Values] b ON a.ID = b.ID
GROUP BY a.Title

我试过了:

public ActionResult Json()
{

    IEnumerable < object > query = (from a in db.Labels
                                    join b in db.Values on a.ID equals b.ID  
                                    group b.ID by a.Title into grp
                                    select new
                                    {
                                        Label = grp.Key,
                                        Value = grp.Count()

                                 }).ToList();

    return Json(query, JsonRequestBehavior.AllowGet);
}

这一结果回报只能有一个值的标签︰

[{"Label":"New","Value":2}]

但我需要的是︰

[
{"Label":"A","Value":2},
{"Label":"B","Value":0},
{"Label":"C","Value":0},
]

解决方法 1:

你为什么不做这︰

IEnumerable < object > query = (from a in db.Labels
                                select new
                                {
                                    Label = a.Title,
                                    Value = db.Values
                                              .Where(w=>w.ID==a.ID)
                                              .Count()
                                 }).ToList();
赞助商