Pedro Nuno
Pedro Nuno

Reputation: 65

How can I simplify code in the foreach loop indexOF?

I've a model with a lot of strings named "hours1, hours2, hours3... " which one is used to assign to the index of the foreach. How can I simplify this code?

if (colNames.IndexOf(item2) == 0)
{
    if (model.Hours == null)
    {
        item.Hours = 0;
    }
    else
    {
        item.Hours = (decimal)model.Hours;

    }
}
if (colNames.IndexOf(item2) == 1)
{
    if (model.Hours1 == null)
    {
        item.Hours = 0;
    }
    else
    {
        item.Hours = (decimal)model.Hours1;
    }
}

if (colNames.IndexOf(item2) == 2)
{
    if (model.Hours2 == null)
    {
        item.Hours = 0;
    }
    else
    {
        item.Hours = (decimal)model.Hours2;
    }

}

Upvotes: 0

Views: 69

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062610

This isn't very pretty, but perhaps:

decimal? hours = null;
switch(colNames.IndexOf(item2))
{
    case 0: hours = model.Hours; break;
    case 1: hours = model.Hours1; break;
    case 2: hours = model.Hours2; break;
}
item.Hours = hours ?? 0M;

Upvotes: 4

Related Questions