我有这样的表:
NAME ITEM COUNT
a x 2
a y 1
b x 3
c z 1
d y 1
d y 1
我已使用此代码计算总数
double sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
}
如何分别计算每个项目的总和,结果应为:
x=5
y=3
z=1
答案 0 :(得分:0)
请按照以下步骤操作:
1)循环通过数据网格。
2)在循环中识别相似的项目(如x,y和z)并将它们相加。
int SumX=0;
int SumY=0;
int SumZ=0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "x")
sumX += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
else if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "y")
sumY += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
else if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "z")
sumZ += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
}
这是example。
使用LINQ查询它非常简单。
int SumX = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(r=> Convert.ToInt32(r.Cells["Item"].Value) == "x")
.Sum(t=> Convert.ToInt32(t.Cells["Count"].Value));
修改强>
如果你真的想让这个求和动态,那么你可以做这样的事情。基本上这里是一个字典来跟踪相同的ITEM,然后总结相应的数量。
Dictionary<string, int> dic = new Dictionary<string, int>();
string item = null;
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
item = dataGridView1.Rows[i].Cells[1].Value.ToString();
if (!dic.ContainsKey(item))
{
dic.Add(item, Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
}
else
{
dic[item] += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
}
}
现在,您可以遍历字典并获取唯一的项目数。
foreach (KeyValuePair<string, int> keyvalue in dic)
{
//get it here
}
希望这会对你有所帮助。
答案 1 :(得分:0)
尝试使用以下方法获取带有求和的分组项的字典:
private Dictionary<string, int> GetSummation()
{
var kvp = new List<KeyValuePair<string, int>>();
for (var i = 0; i < GridView1.Rows.Count; i++)
{
var item = GridView1.Rows[i].Cells[1].Text.Trim();
var count = Convert.ToInt32(GridView1.Rows[i].Cells[2].Text);
kvp.Add(new KeyValuePair<string, int>(item, count));
}
return kvp.GroupBy(k => k.Key).ToDictionary(g => g.Key, g => g.Sum(x => x.Value));
}