简体   繁体   中英

DatagridView C# Sum of columns

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);
}

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)) });

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);
        }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM