获取 DataTable 列的 SUM
Get SUM of DataTable column
我在 DataTable 中有以下值
Affiliate Name | Call
---------------|-----
A | 2
B | 1
B | 0
A | 3
如何检索 Call
对 Affiliate Name
'A' 的总计数。在上面的例子中,它应该 return 5.
foreach (DataRow row in dt.Rows)
{
string CallsOffered = //Get count
}
您可以使用
int CallsOffered=0;
foreach (DataRow row in dt.Rows)
{
if(row["Affiliate_Name"].ToString()=="A")
CallsOffered += int.Parse(row["Call"].ToString());
}
就用
object sumObject = table.Compute("Sum(Call)", "Affiliate_Name = 'A'");
你可以使用DataTable.Compute
方法
var sumOfA = dt.Compute("Sum(Call)", "[Affiliate Name] = 'A'");
或者使用 LINQ
var sumOfA = dt.AsEnumerable()
.Where(dr => dr.Field<string>("Affiliate Name").Equals("A"))
.Sum(dr => dr.Field<int>("Call"));
如果您想获取 Affiliate Name
所有值的调用总和,请使用匿名类型的 LINQ
var results = dt.AsEnumerable()
.GroupBy(dr => dr.Field<string>("Affiliate Name"))
.Select((group, dr) => new
{
AffiliateName = group.Key,
CallsCount = group.Sum(dr.Field<int>("Call")))
});
foreach(var result in results)
{
// Use results
Console.WriteLine($"{result.AffiliateName}: {result.CallsCount}");
}
// with this code you can use linq features in all other steps
// add each column you need them to use them with linq
var records = dt.AsEnumerable().Select(row =>
new
{
Affiliate = row.Field<string>("Affiliate(col name)"),
Call = Convert.ToInt32(row.Field<int>("Call(col name)"))
});
int count = records.Where(q => q.Affiliate == "A").Sum(q => q.Call);
我在 DataTable 中有以下值
Affiliate Name | Call
---------------|-----
A | 2
B | 1
B | 0
A | 3
如何检索 Call
对 Affiliate Name
'A' 的总计数。在上面的例子中,它应该 return 5.
foreach (DataRow row in dt.Rows)
{
string CallsOffered = //Get count
}
您可以使用
int CallsOffered=0;
foreach (DataRow row in dt.Rows)
{
if(row["Affiliate_Name"].ToString()=="A")
CallsOffered += int.Parse(row["Call"].ToString());
}
就用
object sumObject = table.Compute("Sum(Call)", "Affiliate_Name = 'A'");
你可以使用DataTable.Compute
方法
var sumOfA = dt.Compute("Sum(Call)", "[Affiliate Name] = 'A'");
或者使用 LINQ
var sumOfA = dt.AsEnumerable()
.Where(dr => dr.Field<string>("Affiliate Name").Equals("A"))
.Sum(dr => dr.Field<int>("Call"));
如果您想获取 Affiliate Name
所有值的调用总和,请使用匿名类型的 LINQ
var results = dt.AsEnumerable()
.GroupBy(dr => dr.Field<string>("Affiliate Name"))
.Select((group, dr) => new
{
AffiliateName = group.Key,
CallsCount = group.Sum(dr.Field<int>("Call")))
});
foreach(var result in results)
{
// Use results
Console.WriteLine($"{result.AffiliateName}: {result.CallsCount}");
}
// with this code you can use linq features in all other steps
// add each column you need them to use them with linq
var records = dt.AsEnumerable().Select(row =>
new
{
Affiliate = row.Field<string>("Affiliate(col name)"),
Call = Convert.ToInt32(row.Field<int>("Call(col name)"))
});
int count = records.Where(q => q.Affiliate == "A").Sum(q => q.Call);