Reputation: 47
Hello I'm wondering how can I get the sum of a column according with the value in another column. For example I have a DatagridView like this
User Value to sum
-------------------
User1 10
-------------------
User1 15
-------------------
User2 20
-------------------
User3 30
I want to know how can I get the sum for each user.
Expected output
User1: 25
User2: 20
User3: 30
So far I have the code for get the sum of all users but I don't know hot to get per user.
Thanks in advance for everyone.
for (int i = 0; i < dataGridView2.Rows.Count-1; i++)
{
total += Convert.ToInt32(dataGridView2.Rows[i].Cells[ColumnN].Value);
}
Upvotes: 0
Views: 3190
Reputation: 460128
You could use this query:
var userSums = dataGridView2.Rows.Cast<DataGridViewRow>()
.GroupBy(row => row.Cells[0].Value.ToString())
.Select(g => new { User = g.Key, Sum = g.Sum(row => Convert.ToInt32(row.Cells[1].Value)) });
Upvotes: 1
Reputation: 2439
If you extract your data as a list of pairs you can use the codes below:
var data = new List <KeyValuePair<string, int>>()
{
new KeyValuePair<string, int>( "User1", 10 ),
new KeyValuePair<string, int>( "User1", 15 ),
new KeyValuePair<string, int>( "User2", 20 ),
new KeyValuePair<string, int>( "User3", 30 )
};
var res = data.GroupBy(x => x.Key);
foreach (var item in res)
{
var user = item.ToList();
var sum = item.Sum(x => x.Value);
Console.WriteLine(user[0].Key + " " + sum);
}
Upvotes: 0