mercredi 4 mars 2015

Optimizing code structure C#

Here's code I write to check if properties in my viewmodel are null or not before attempting to update the database



var channel = _context.Channels.FirstOrDefault(x => x.Id == viewModel.Id);

if (!string.IsNullOrEmpty(viewModel.Part))
{
channel.Part = viewModel.Part;
}
if (!string.IsNullOrEmpty(viewModel.IndexName))
{
channel.IndexName = viewModel.IndexName;
}
if (viewModel.MeasurementId != null)
{
channel.MeasurementId = viewModel.MeasurementId;
}
if (!string.IsNullOrEmpty(viewModel.Direction))
{
channel.Direction = viewModel.Direction;
}


The code is working fine but I use alot of if statements here which for me doesn't look really effective. Can you suggest me changes like using other syntax or structures rather than if statement to make my code more concise and abit more "pro"?


Aucun commentaire:

Enregistrer un commentaire