的SUM我DataTable中獲取數據表列
Affiliate Name | Call
---------------|-----
A | 2
B | 1
B | 0
A | 3
以下值我怎樣才能檢索到的Call
總數針對Affiliate Name
'A'。在上面的例子,它應該返回5.
foreach (DataRow row in dt.Rows)
{
string CallsOffered = //Get count
}
的SUM我DataTable中獲取數據表列
Affiliate Name | Call
---------------|-----
A | 2
B | 1
B | 0
A | 3
以下值我怎樣才能檢索到的Call
總數針對Affiliate Name
'A'。在上面的例子,它應該返回5.
foreach (DataRow row in dt.Rows)
{
string CallsOffered = //Get count
}
您可以使用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的所有值與b在dataTable.AsEnumerable()用b B組匿名類型
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}");
}
您可以使用
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'");
// 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);
VAR groupedData = 。Field(「Affiliate Name」)into g select new { Affiliate Name = g.Key, Count = g.Count(), Call = g.Su m(x => x.Field (「Call」)) }; –
[如何計算asp.net中datatable列的總和?](http://stackoverflow.com/questions/5892993/how-to-calculate-the-sum-of-the-datatable-column -in-asp-net) – Daniel
@Daniel它不是一個簡單的SUM。「Call」的總和取決於另一列的值 –