I am trying to loop over a DataTable in c# and get the values from the cells. The data received back could look something like this depending on the number of months selected.
Total Year Month TypeId
466 2018 1 1
77 2018 1 2
471 2018 2 1
58 2018 2 2
459 2018 3 1
151 2018 3 2
Month 1 being equal to January. How would I split up this data based on dates entered so if someone is looking for March data I would want to add up the totals for March (459 + 151)
Here is my code at moment.
if (ds.Tables.Count > 0)
{
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
result.Total = Convert.ToInt32(ds.Tables[0].Rows[0]["Total"]);
}
}
}
You are iterating through the rows of all tables, but then you are always using the first row of the first table. This will obviously give you the wrong result. You have to use the value of the current row. If you want to only include the march values, you need to skip all other rows:
if (ds.Tables.Count > 0)
{
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
if (Convert.ToInt32(row["Month"]) != 3)
{
continue;
}
result.Total = Convert.ToInt32(row["Total"]);
}
}
}
Note that this assumes that all tables in your dataset have at least a "Month" and a "Total" column. Most real-world datasets do not look like this. Since you do not show us the dataset, I assume that this actually is the underlying structure.
请在下面使用以获取进行总额。
int sum = Convert.ToInt32(dt1.Compute("SUM(Total)", "Month = 3"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.