我在DataTable中有以下值
Affiliate Name | Call
---------------|-----
A | 2
B | 1
B | 0
A | 3
如何针对Call
' A'检索Affiliate Name
的总计数。在上面的示例中,它应该返回5.
foreach (DataRow row in dt.Rows)
{
string CallsOffered = //Get count
}
答案 0 :(得分:5)
您可以使用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}");
}
答案 1 :(得分:0)
您可以使用
int CallsOffered=0;
foreach (DataRow row in dt.Rows)
{
if(row["Affiliate_Name"].ToString()=="A")
CallsOffered += int.Parse(row["Call"].ToString());
}
答案 2 :(得分:0)
只需使用
object sumObject = table.Compute("Sum(Call)", "Affiliate_Name = 'A'");
答案 3 :(得分:0)
// 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);