Pedro Nuno
Pedro Nuno

Reputation: 65

how to simplify the switch case statement in MVC model?

i've this code to insert in DB the data from the "hours1, hours2, hours3" that cames from an excel import, but this makes the code bigger by the way im doing, this is my code, how can i simplfy the part of the hours1,hours2 == nulls.. ?

switch (colNames.IndexOf(item2))
{
    case 0:
        if (model.Hours == null)
        {
            item.Hours = 0;
        }
        else
        {
            item.Hours = (decimal)model.Hours;
            item.Hours_Remaining = (decimal)model.Hours;
        }
        break;
    case 1:
        if (model.Hours1 == null)
        {
            item.Hours = 0;
        }
        else
        {
            item.Hours = (decimal)model.Hours1;
            item.Hours_Remaining = (decimal)model.Hours;
        }
        break;
    case 2:
        if (model.Hours2 == null)
        {
            item.Hours = 0;
        }
        else
        {
            item.Hours = (decimal)model.Hours2;
            item.Hours_Remaining = (decimal)model.Hours;
        }
        break;
    case 3:
        if (model.Hours == null)
        {
            item.Hours = 0;
        }
        else
        {
            item.Hours = (decimal)model.Hours3;
            item.Hours_Remaining = (decimal)model.Hours;
        }
        break;
} 

Upvotes: 1

Views: 57

Answers (1)

Shantanu
Shantanu

Reputation: 554

you can have a private method like this

private void NameOfPrivateMethod(object objValue,Hours hours,Item item)
        {
            if (objValue == null)
            {
                item.Hours = 0;
            }
            else
            {
                item.Hours = (decimal)objValue;
                item.Hours_Remaining = (decimal)hours;
            }
        }

and use it like this (you need to make some changes to it according to your need)

NameOfPrivateMethod(model.Hours1, model.Hours,Item)

Upvotes: 2

Related Questions