I added a new column in one of my table and the result of this column depends on the result of 2 other columns. I did a update so I can fill the existing rows with information but I would also like to transform the case statement into a LINQ query for my code.
UPDATE depotProjet.Projets
SET IdPlateformeSecteur =
CASE
WHEN (IdPlateforme = 1 AND IdSecteur = 1) then 1
WHEN (IdPlateforme = 1 AND IdSecteur = 2) then 2
WHEN (IdPlateforme = 1 AND IdSecteur = 4) then 3
WHEN (IdPlateforme = 3 AND IdSecteur = 1) then 4
WHEN (IdPlateforme = 3 AND IdSecteur = 2) then 5
WHEN (IdPlateforme = 3 AND IdSecteur = 4) then 6
WHEN (IdPlateforme = 2 AND IdSecteur = 1) then 7
WHEN (IdPlateforme = 2 AND IdSecteur = 2) then 8
WHEN (IdPlateforme = 2 AND IdSecteur = 4) then 9
End
WHERE IdPlateformeSecteur is NULL;
this is what I'm coming up with:
if (projet.IdPlateforme == 1 && projet.IdSecteur == 1)
{
projet.IdPlateformeSecteur = 1;
}
else if (projet.IdPlateforme == 1 && projet.IdSecteur == 2)
{
projet.IdPlateformeSecteur = 2;
}
else if (projet.IdPlateforme == 1 && projet.IdSecteur == 4)
{
projet.IdPlateformeSecteur = 3;
}
else if (projet.IdPlateforme == 3 && projet.IdSecteur == 1)
{
projet.IdPlateformeSecteur = 4;
}
else if (projet.IdPlateforme == 3 && projet.IdSecteur == 2)
{
projet.IdPlateformeSecteur = 5;
}
else if (projet.IdPlateforme == 3 && projet.IdSecteur == 4)
{
projet.IdPlateformeSecteur = 6;
}
else if (projet.IdPlateforme == 2 && projet.IdSecteur == 1)
{
projet.IdPlateformeSecteur = 7;
}
else if (projet.IdPlateforme == 2 && projet.IdSecteur == 2)
{
projet.IdPlateformeSecteur = 8;
}
else if (projet.IdPlateforme == 2 && projet.IdSecteur == 4)
{
projet.IdPlateformeSecteur = 9;
}
my search are giving me example with select but I dont have a select. It's working but I would like to do it the proper way . Thank you
I made some assumptions based off of your
depotProjet.Projet
model with the below class, but should be close enough to accomplish what you're wanting:(Link to working DotNet Fiddle: https://dotnetfiddle.net/i2RAx3)
You can use a
Func<int, int, int>
to pass in theIdPlatforme
andIdSecteur
to move theif
statement out of your query (the below uses recursive pattern matching and requires C# 8.0 or greater, otherwise you can replace it withcase
statement):Then you can query your Projects database and return an anonymous type that includes the fields from your Project model you added
IdPlateformeSecteur
like this:Full LINQPad example below: