Home > Net >  Replace If else in C Sharp
Replace If else in C Sharp

Time:10-29

This is my Business Layer Code public void UpdateRecords() {

int resultCountries = 0
int resultState = 0
int resultDistrict = 0
int resultCity = 0
DataTable dt = dataAccess.GetRecords();
foreach(DataRow dr in dt.Rows)
{    
    int PersonId = Convert.ToInt32(dr["PersonId"].ToString());
    resultCountries = dataAccess.UpdateCountries(PersonId);
    if(resultCountries > 0)
    {
        dataAccess.UpdateMessage(personId,"Country Updated Successfully");
        resultState = UpdateState(personId);
        if(resultState > 0)
        {
            dataAccess.UpdateMessage(personId,"State Updated Successfully");    
            resultDistrict = UpdateDistrict(personId);
            if(resultDistrict > 0)
            {
                dataAccess.UpdateMessage(personId,"District Updated Successfully");
                resultCity = UpdateCity(personId);
                if(resutlCity > 0)
                {
                    dataAccess.UpdateMessage(personId,"City Updated Successfully");
                    continue;
                }
                else if(resutlCity == 0)
                {
                    dataAccess.UpdateMessage(personId,"City Not Updated Successfully");
                    continue;
                }
                else
                {
                    dataAccess.UpdateMessage(personId,"Some error occured while updating city...");
                    continue;            
                }        
        
            }
            else if(resultDistrict  == 0)
            {
                dataAccess.UpdateMessage(personId,"District not Updated Successfully");
                continue;
            }
            else
            {
                dataAccess.UpdateMessage(personId,"Some error occured while updating district..");
                continue;
            }        
        }
        else if(resultState  == 0)
        {
                dataAccess.UpdateMessage(personId,"State not Updated Successfully");
                continue;
        }
        else
        {
            dataAccess.UpdateMessage(personId,"Some error occured while updating state..");
            continue;
        }        
    }
    else if(resultCountries == 0)
    {
        dataAccess.UpdateMessage(personId,"Country not Updated Successfully");
        continue;
    }
    else 
    {
        dataAccess.UpdateMessage(personId,"Some error occured");
        continue;
    }
}

}

From business Layer I am calling data access layer methods,UpdateCountries,UpdateState,UpdateDistrict,UpdateCity which are updating country, state,district,city against personId in person table.

If country update is successful,state is updated otherwise log the error in db and update next record. Same is done for state,district,city. But here there are lots of if else used,kindly let me know how to replace if else in code. Do not want to use switch case or ternary operator,also not allowed to use stored procedure. The dataaccess layer methods return integer value of 1 if update is successfull,0 if condition is not satisfied,-1 if error.

CodePudding user response:

For academic intrigue and curiosity only

You could use a list of delegate

var list = new List<(string Name, Func<int, int> Callback)>()
{
   ("Country", dataAccess.UpdateCountries),
   ("State", dataAccess.UpdateState),
   ("District", dataAccess.UpdateDistrict),
   ("City", dataAccess.UpdateCity),
};


DataTable dt = dataAccess.GetRecords();

foreach (DataRow dr in dt.Rows)
{
   var personId = Convert.ToInt32(dr["PersonId"].ToString());
   foreach (var (name, callback) in list)
   {
      switch (callback(personId))
      {
         case > 0:
            dataAccess.UpdateMessage(personId, $"{name} Updated Successfully");
            continue;
         case 0:
            dataAccess.UpdateMessage(personId, $"{name} not Updated Successfully");
            break;
         default:
            dataAccess.UpdateMessage(personId, "Some error occurred");
            break;
      }

      break;
   }
}

However

You should be doing this all in the one request and one round trip to the database, as such this problem should likely be rethought and refactored.

CodePudding user response:

As it appears that you're using the result of your update process to determine whether to process the next dependency and change the wording of an indication message then perhaps you could use a Dictionary For example something along the lines of:

   var messageDictionary = new Dictionary<int, string>()
   {
       { 1, "Updated Successfully" },
       { 0, "Not updated successfully"},
       {-1, "Some error occurred while updating "}
   };

Then as a first pass you if..else... logic would become:

int PersonId = Convert.ToInt32(dr["PersonId"].ToString());
var result = dataAccess.UpdateCountries(PersonId);
dataAccess.UpdateMessage(personId, $"Country {messageDictionary[result]}");

if (result > 0)
{
    result = UpdateState(personId);
    dataAccess.UpdateMessage(personId, $"State {messageDictionary[result]}");
    if (result >0)
    {
        result = UpdateDistrict(personId);
        dataAccess.UpdateMessage(personId, $"District {messageDictionary[result]}");
        if (result > 0)
        {
            result = UpdateCity(personId);
            dataAccess.UpdateMessage(personId, $"City {messageDictionary[result]}");
        }
    }
}

If you implemented the suggestion by @TheGeneral then you would have:

foreach (DataRow dr in dt.Rows)
{
   var personId = Convert.ToInt32(dr["PersonId"].ToString());
   foreach (var (name, callback) in list)
   {
      var result = callback(personId);
      dataAccess.UpdateMessage(personId, $"{name} {messageDictionary[result]}");
      if(result!=1) break;
   }
}
  • Related