我有以下数据
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()
});
任何帮助?
答案 0 :(得分:1)
在我看来,唯一的问题是你要分组两次。我希望这可行:
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)
});
答案 1 :(得分:1)
您无需分组两次即可获得所需的结果。一个分组就可以了:
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()
});