1

I have a task to find even or odds numbers in a list using LINQ lambda. I simply have this code to do it, but the compiler says "not all code paths return a value in lambda expression". So I think I need a default value, but how can I implement it? I tried a few things but still don't work. Please give advice. Thanks.

 list = list.Where(x =>
        {
            if (command == "odd")
                return x % 2 != 0;

            else if (command == "even")
                return x % 2 == 0;

        });
max plant
  • 25
  • 2
  • What do you mean by "default value"? You mean else case? – Fatih TAN Jun 12 '20 at 08:32
  • Can you clarify object's properties in list? – Fatih TAN Jun 12 '20 at 08:33
  • you need to decide what to do if the value is neither "odd" or "even". Sensible options would include : return `null` (and in this case the result would be an `IEnumerabl`, or throw an exception. – Pac0 Jun 12 '20 at 08:34
  • 2
    If someone did `command = "NotOddOrEven";` what would your lambda return? It's your human mind that knows that `command` can only have the values "odd" or "even" but the compiler does not know that. –  Jun 12 '20 at 08:38

2 Answers2

1

If the command is "notEvenOrOdd" what should be the result? The example code does not cover this case, and it will therefore fail.

Using a "command" to determine what to do is usually not a great design. An alternative would be two extension methods:

public static IEnumerable<int> WhereEven(this IEnumerable<int> list) => list.Where(x => x % 2 != 0);
public static IEnumerable<int> WhereOdd(this IEnumerable<int> list) => list.Where(x => x % 2 == 0);

You can then check the command outside the lambda and run one of the methods above depending on the result.

JonasH
  • 28,608
  • 2
  • 10
  • 23
-1

I meant if the if-else statement dont match the conditions. I tried this and it works.

list = list.Where(x =>
        {
            if (command == "odd")
                return x % 2 != 0;

            else if (command == "even")
                return x % 2 == 0;

            return false;

        }).ToList();
max plant
  • 25
  • 2
  • The warning is because if you only have an `if` and `else-if` it's possible that `command`, being a string, might not match any of those and thus wouldn't hit any return point. If you change `else if` to just `else` you can drop the `return false` at the end but that assumes `command` can truly only be "odd" or "even". – WSC Jun 12 '20 at 08:44
  • it solves the compiler error, but I am not sure if I would recommend this. For instance, imagine the developper makes a Typo, and write `"Even"` as command. Then, everything will return `false`, including the even numbers in the list. And you might not notice the bug until much later. See the other answer from JonasH for a more defensive approach. – Pac0 Jun 12 '20 at 12:22