我得到了以下数据
title |有用
ttitle1|是
ttitle1|是
ttitle1|无
ttitle2|是
我想把上面的数据分组并压平,这样我就得到了以下结果:
标题|有用计数|无效计数
tttitle1|2|1
tttitle2|1|0
尝试过这个,但没有产生正确的结果:
var query = (from r in ratings
group r by new { r.ArticleTitle, r.Useful } into results
group results by new { results.Key.ArticleTitle } into results2
from result in results2
select new
{
Title = result.Key.ArticleTitle,
Yes = result.Select(i => i.Useful).Count(),
No = result.Select(i => i.Useful == false).Count()
});
有什么帮助吗?
在我看来,唯一的问题是分组两次。我希望这能奏效:
var query = from rating in ratings
group rating by rating.ArticleTitle into g
select new
{
Title = g.Key,
Yes = g.Count(r => r.Useful),
No = g.Count(r => !r.Useful)
};
或者不在查询表达式形式中:
var query = ratings.GroupBy(r => r.ArticleTitle,
(key, rs) => new
{
Title = key,
Yes = rs.Count(r => r.Useful),
No = rs.Count(r => !r.Useful)
});
您不需要分组两次就可以获得所需的结果。一个分组就可以了:
var query = (from r in ratings
group r by new { r.ArticleTitle } into g
from result in groups
select new
{
Title = result.Key,
Yes = result.Select(i => i.Useful).Count(),
No = result.Select(i => !i.Useful).Count()
});