I have the following code -> something like Select case using LINQ –
This is not the actual code [picked from internet].
Just trying to show the Select Case concept using LINQ.
In my code, based on the conditions I am creating new List objects
Int32[] numbers = new Int32[] { 1, 2, 1, 3, 1, 5, 3, 1 };
var numberText =
(
from n in numbers
where n > 0
select new
{
Number = n,
Text =
(
n == 1 ? "One" :
n == 2 ? "Two" :
n == 3 ? "Three" : "Unknown"
)
}
);
But, the page here says – “Replace condition with polymorphism”.
So, the question is whether such kind of implementation is a code smell and should it always be strictly avoided ? LINQ seems like an obvious choice while looping through collections and creating new objects conditionally. May be its wrong ?
There is a fundemental difference. LINQ is an API that allows you to query collections (as you have demonstrated in your question). A switch (or other conditional) statement is used to control program flow.
The page you are referring to is talking about refactoring code when you have a lot of conditional statements controlling program flow based on some type – in this case it suggests that you may want to replace all the conditionals with some poly-morphism. So in this case there is a code smell. But using conditionals in a LINQ statement is OK – there are probably many ways to structure your LINQ – some will perform better than others, and some will read better than others, but I would not say using conditionals in LINQ is a code smell.