Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

Please see below:

C#
int i = 0;
           foreach (DataGridViewRow dgr in this.dataGridView1.Rows)
           {
               dgr.DefaultCellStyle.BackColor = ((i % 2) == 0) ? Color.LightGray : Color.DarkGray;
               i++;
           }


Can anybody tell me how the above code can be converted into LINQ please?

Many thanks in advance
Posted
Comments
joshrduncan2012 7-Feb-13 10:25am    
What have you tried so far?

Best solution I can come up with is

Buy ReSharper, and there is a function to convert foreach into LINQ.

That's what I have used in the past, and miss it now :(

http://www.jetbrains.com/resharper/[^]
 
Share this answer
 
First, why do this in LINQ? The code you have does the job without it, so I'd suggest taking a look at why it is necessary to change.

If you want to you could clean you line a little:
C#
bool isOddRow = true;
foreach (DataGridViewRow dgr in this.dataGridView1.Rows)
{
    dgr.DefaultCellStyle.BackColor = isOddRow ? Color.LightGray : Color.DarkGray;
    isOddRow = !isOddRow;
}


One positive change you could make is to take advantage of AlternatingRowsDefaultCellStyle and RowsDefaultCellStyle, which would probably make the above redundant totally, see MSDN for examples.
 
Share this answer
 
Comments
Member1978 7-Feb-13 14:50pm    
Thanks Keith
You are Geordie then. I went to Newcastle Polytechnic many years ago. I agree with you people up in Newcastle are very kind indeed. I had such a good time there.
Cheers for the solution.
Keith Barrow 7-Feb-13 15:04pm    
I am indeed, born & bred. I almost went to Northumbria Uni (hasn't been a Poly since my undergrad days in the mid 90s) to read my MSc, but the course at Newcastle suited my needs better as it had less emphasis on DB work. Glad to be of help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900