-
Jun 23rd, 2016, 09:19 AM
#1
Thread Starter
Frenzied Member
Get column sum of DataGridView
Is there a way to get the sum of a column in an unbound DGV without looping through the rows? Perhaps a Linq query?
-
Jun 23rd, 2016, 03:07 PM
#2
Re: Get column sum of DataGridView
Code:
MsgBox(DataGridView1.Rows.Cast(Of DataGridViewRow).Sum(Function(r) Val(r.Cells(0).Value)))
where Cells(0) refers to the columnIndex 0
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Jun 23rd, 2016, 03:13 PM
#3
Thread Starter
Frenzied Member
Re: Get column sum of DataGridView
Hi Paul ... thanks for the reply. After some searching I came up with this line, which works also, but seems to be structured a little differently than yours. Is one method better than the other, or are they essentially the same?
Code:
sum = (From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Select CDbl(row.Cells(0).Value)).Sum
-
Jun 23rd, 2016, 03:20 PM
#4
Re: Get column sum of DataGridView
Essentially, they do the same task, and both are equally correct. I wouldn't use CDbl though. Val returns a Double and doesn't throw an error if the cell value is Nothing..
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Jun 23rd, 2016, 03:22 PM
#5
Re: Get column sum of DataGridView
Personally, I'd use my version as the Select function in your method is redundant...
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Jun 23rd, 2016, 10:03 PM
#6
Re: Get column sum of DataGridView
Those two code snippets would compile to basically the same IL and possibly exactly the same IL. The query syntax that you used is just syntactic sugar and it's actual methods that end up getting executed. .paul. has specified those methods explicitly in the function syntax that he has used. Personally, I tend to use function syntax more often but there are times that query syntax feels more natural. Both are equally valid.
As for your Select being redundant, I wouldn't agree. If you were using function syntax then to call Select followed by Sum would be redundant but having a Select clause in your query is fine. Different strokes though. Again, none are outright wrong. The fact that you have to call Sum anyway and are therefore mixing query syntax and function syntax is an example of why I tend to lean towards function syntax most of the time.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|