如何在C#中将Linq计数与group by一起使用

时间:2018-08-27 03:20:06

标签: c# linq datatable

我有一个数据表,看起来像这样
datatable input
基本上,我希望它按列FeatureName(distinct)分组,在该列中应进行汇总并完成列
指定所有特征ID,以逗号分隔的特征名称
特征ID的数量
分配给comman分隔的
现在我希望数据表看起来像这样
enter image description here
不知道如何使用计数 代码

var result5= dtTaskandBugs.AsEnumerable().GroupBy(x => x["Functional Area"])
                               .Select(item => new
                               {
                                   FunctionalArea = item.Key,

                                   Completedsum = item.Sum(y => Convert.ToDecimal(y["Completed"])),
                                   effortsum = item.Sum(z => Convert.ToDecimal(z["effort"])),
                                   storyids = string.Join(",", item.Select(a => a["Storyid"]).Distinct()),
                                   storiesename= string.Join(",", item.Select(b => b["StoryName"]).Distinct()),
                                   Featureid = string.Join(",", item.Select(c => c["Featureid"]).Distinct()),
                                   Featurename= string.Join(",", item.Select(d => d["FeatureName"]).Distinct()),

                               });

2 个答案:

答案 0 :(得分:3)

使用Count(),您将获得分组值的计数。 像这样尝试Linq

from s in dtTaskandBugs.AsEnumerable()
                        group s by s.Field<string>("Functional Area")
                            into grp
                            orderby grp.Key
                            select new { 
                                   FunctionalArea = grp.Key,
                                   Completedsum = grp.Sum(y => Convert.ToDecimal(y["Completed"])),
                                   effortsum = grp.Sum(z => Convert.ToDecimal(z["effort"])),
                                   storyids = string.Join(",", grp.Select(a => a["Storyid"]).Distinct()),
                                   storiesename= string.Join(",", grp.Select(b => b["StoryName"]).Distinct()),
                                   Featureid = string.Join(",", grp.Select(c => c["Featureid"]).Distinct()),
                                   Featurename= string.Join(",", grp.Select(d => d["FeatureName"]).Distinct()),
                                   Count = grp.Count()          // <----------------
 };

答案 1 :(得分:0)

只需编写item.count(),您将获得分组值的计数,