HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Refactoring code into a simpler method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
refactoringmethodintosimplercode

Problem

I have some code that loops over a number and populates a list using other lists. I think I can refactor it somehow to make it look nicer but not sure the best way to do it.

Here is the code:

```
for (int i = 0; i i)
ExpectedValues.Add(InputList1[i]);
break;
case 2:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
break;
case 3:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
break;
case 4:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
break;

case 5:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
if (InputList5.Count > i)
ExpectedValues.Add(InputList5[i]);
break;
case 6:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if

Solution

The alternate method of Dr. Andrew Burnett-Thom would be to use a Dictionary:

var dic = new Dictionary();
    // add InputLists
    dic.Add(0, InputList1);
    dic.Add(1, InputLIst2);
    //etc...

    for( int i = 0; i  i )
            {
                ExpectedValues.Add( dic[j][i] );
            }
        }
    }

Code Snippets

var dic = new Dictionary<int, InputList>();
    // add InputLists
    dic.Add(0, InputList1);
    dic.Add(1, InputLIst2);
    //etc...

    for( int i = 0; i < loopCount; i++ )
    {
        for( int j = 0; j < NoOfRows; j++ )
        {
            if( dic[j].Count > i )
            {
                ExpectedValues.Add( dic[j][i] );
            }
        }
    }

Context

StackExchange Code Review Q#11245, answer score: 2

Revisions (0)

No revisions yet.