Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list with 2 columns using foreach

Tags:

c#

I have a list that is just 1 row initially as such:

    One
    Two
    Three
    Four
    Five 
    Six
    Seven

I would then have the following in a list - note how I have 2 columns - first column is for odd number, second column is for even number:

    One     Two
    Three   Four
    Five    Six
    Seven

I am trying the following:

foreach(var item in mod)
{
    int i = 0;

    i = i + 1;
    if (i % 2 == 0) 
    {                  
        //add to list here for even number 
    }

    if (i % 2 != 0)
    {
        // add to list here for odd number
    } 
}  
like image 940
Nate Pet Avatar asked Dec 16 '22 04:12

Nate Pet


1 Answers

I'd suggest LINQ:

var odds = mod.Where((item, index) => index % 2 == 0).ToList();
var evens = mod.Where((item, index) => index % 2 == 1).ToList(); 
like image 126
tzaman Avatar answered Jan 06 '23 07:01

tzaman