Linq Group通过多个字段和Flatten列表

时间:2016-07-22 04:46:22

标签: c# linq group-by

我有以下数据

标题|有用

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()
                    });

任何帮助?

2 个答案:

答案 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()
             });