我有一张表格,其中包含地区,地区,投诉和案件状态。我想做的是:
这是到目前为止的代码。问题是计数总是返回0,这会引发错误。
foreach (DataRow mainrow in CaseTable.Rows)
{
RegionName = mainrow.Field<string>("Region");
DistrictName = mainrow.Field<string>("DistrictName");
if (mainrow.Field<string>("CaseStatus") == "Resolved")
DistrictcaseCount++;
DistrictcaseCount++;
PercentageResolved = (DistrictResolvedCount / DistrictResolvedCount) * 100;
PercResolved = PercentageResolved.ToString() + "%";
ReportTable.Rows.Add(RegionName, DistrictName, DistrictcaseCount, DistrictResolvedCount, PercResolved);
}
答案 0 :(得分:0)
您的问题中的代码段似乎存在多个问题。
DistrictcaseCount
而不是DistrictResolvedCount
DistrictResolvedCount
除以自身来计算百分比。DistrictResolvedCount / DistrictcaseCount
,它将始终为0,因为它们是整数。我相信这会做你想要的:
// This will count cases and resolved cases, grouped by district.
var districtGroups =
from row in CaseTable.Rows
group row by new {
Region = row.Field<string>("Region"),
District = row.Field<string>("DistrictName")
} into g
select new {
Region = g.Key.Region,
District = g.Key.District,
CaseCount = g.Count(),
ResolvedCaseCount = g.Count(r => "Resolved".Equals(r.Field<string>("CaseStatus")))
};
// this will calculate the percentage and add the rows.
foreach (var entry in districtGroups)
{
// determine percentage.
string percentageResolved;
if (entry.CaseCount > 0)
{
var percent = (100.0 * entry.ResolvedCaseCount) / CaseCount;
percentageResolved = percent.ToString() + "%";
}
else // What to do if there are no cases?
{
percentageResolved = "N/A";
}
// add row for the district.
ReportTable.Rows.Add(
entry.Region, entry.District,
entry.CaseCount, entry.ResolvedCaseCount,
percentageResolved);
}
答案 1 :(得分:0)
@Alex我修复了这些问题。非常感谢你的代码。我最终得到了这个:
var districtGroups =来自CaseTable.Rows.Cast()中的行 按行分组 { Region = row.Field(&#34; Region&#34;), District = row.Field(&#34; DistrictName&#34;) 进入g 选择新的 { Region = g.Key.Region, 区= g.Key.District, CaseCount = g.Count(), ResolvedCaseCount = g.Count(r =&gt;&#34;已解决&#34; .Equals(r.Field(&#34; CaseStatus&#34;))) };
// this will calculate the percentage and add the rows.
foreach (var entry in districtGroups)
{
// determine percentage.
string percentageResolved;
if (entry.CaseCount > 0)
{
var percent = (100.0 * entry.ResolvedCaseCount) / entry.CaseCount;
percentageResolved = percent.ToString() + "%";
}
else // What to do if there are no cases?
{
percentageResolved = "N/A";
}
// add row for the district.
ReportTable.Rows.Add(
entry.Region, entry.District,
entry.CaseCount, entry.ResolvedCaseCount,
percentageResolved);
}