[英]How to use group by on a DataTable in LINQ?
I have DataTable
with columns: 我有带有列的
DataTable
:
Column1, Column2, Column3, Column4
I need to select: 我需要选择:
sum Column1, Count Distinct (Column2), Column3, Column4
group by Column3, Column4 按Column3,Column4分组
I am using this code but with wrong result in count distinct 我正在使用此代码,但计数结果错误
var queryDGroup = dtsecscaleditemsCloned2.AsEnumerable()
.GroupBy(r => new { Col1 = r["Column3"], Col2 = r["Column4"]});
foreach (var g in queryDGroup)
{
DataRow addedRow = dtsecscaleditemsCloned.Rows.Add();
addedRow["Column1"] = g.Distinct ().Count();
addedRow["Column4"] = g.Key.Col2;
addedRow["Column3"] = g.Key.Col1;
addedRow["store_Code"] = "";
addedRow["Column2"] = g.Sum(r => r.Field<int>("Column2"));
}
As far as I could understand, you're trying to count the distinct values in the Column2
column. 据我了解,您正在尝试计算
Column2
列中的不同值。 You need to project to that column first before doing anything else. 您需要先投影到该列,然后再执行其他操作。 Otherwise you're just counting distinct
DataRow
instances (which will have no meaning here). 否则,您只是在计数不同的
DataRow
实例(此处没有任何意义)。
I'd write it like this: 我会这样写:
var query =
from r in dt.AsEnumerable()
group new
{
Column1 = r.Field<int>("Column1"),
Column2 = r.Field<int>("Column2"),
}
by new
{
Column3 = r.Field<string>("Column3"),
Column4 = r.Field<string>("Column4"),
}
into g
select new
{
Column1 = g.Select(x => x.Column1).Distinct().Count(), // project first
Column2 = g.Sum(x => x.Column2),
g.Key.Column3,
g.Key.Column4,
StoreCode = "",
};
You can try this: 您可以尝试以下方法:
var queryDGroup = dataTable.AsEnumerable()
.GroupBy(c => new { Col3 = c["Column3"], Col4 = c["Column4"] },
x => x,
(k, g) => new
{
Col1Sum = g.Sum(t => t.Field<int>("Column1")),
Col2Count = g.Select(t => t.Field<int>("Column2")).Distinct().Count()
}).FirstOrDefault();
The object queryDGroup
is an anonymously typed object with two properties: Col1Sum
and Col1Count
(the names are self-explanatory). 对象
queryDGroup
是具有两个属性的匿名类型对象: Col1Sum
和Col1Count
(名称是不言自明的)。
You can either create strongly typed anonymous objects as you select elements while doing group by (the second parameter to the GroupBy
), or cast to individual column's datatypes in the result selector part (the last parameter to the GroupBy
), as I have shown here. 您可以在进行分组依据时选择元素时创建强类型的匿名对象(
GroupBy
的第二个参数),或者在结果选择器部分将其GroupBy
为单个列的数据类型( GroupBy
的最后一个参数),如我在此处所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.