2

I'm trying to write a lambda like below but my syntax is incorrect.

Result = ListOfNumbers.Where(val => { val != Num1; val != Num2; }).ToList()[0];

The error I get is

Not all code paths return a value in lambda expression of type 'System.Func<int,int,bool>'

Perhaps there's a better way of doing this... I know there's the numbers 1, 2 and 3 (in that order) in ListOfNumbers. Num1 and Num2 at this point will both be either 1, 2 or 3 (they can't be the same though). I want my result to be the 'other' number from ListOfNumbers. Hope that's clear. If you can think of a neater way of doing it I'd love to hear it.

Any thoughts?

4

7 回答 7

2

you need to change it to

val => val != Num1 && val != Num2 

If I write the code you've provided as it would be as a function you might see what's wrong:

public bool Predicate(int val)
{
   val != Num1;
   val != Num2;
}

I.e. - where's the return statement?

Although - note that that will actually fail to compile with the error Only assignment, call, increment, decrement, and new object expressions can be used as a statement - the compiler rules in lambdas are slightly different and so you get a different error but ultimately it's for the same kind of reason - in your case none of your lambda paths return anything.

于 2012-06-22T10:52:53.250 回答
1

Change the lambda as:

ListOfNumbers.Where(val =>  val != Num1 && val != Num2)
于 2012-06-22T10:52:45.917 回答
1

Did you actually want to do this?

Result = ListOfNumbers.Where(val => val != Num1 && val != Num2).ToList()[0];

Also, what if the list has no elements? You should better check that before accessing it by index.

于 2012-06-22T10:53:21.953 回答
1

You are getting the error because inside Where clause you are not getting any bool, you need to change your lambda expression to :

Result = ListOfNumbers.Where(val =>  val != Num1 && val != Num2).ToList()[0];
于 2012-06-22T10:55:15.590 回答
0

As your code expecting System.Func<int,int,bool> delegate which returns boolean value as in where condition So, you should define it in following way:

Result = ListOfNumbers.Where(val => { val != Num1 && val != Num2; }).ToList()[0];
于 2012-06-22T10:57:02.377 回答
0

I think you want to produce something like this :

Result = ListOfNumbers.Where(val => val != Num1 && val != Num2).ToList()[0];
于 2012-06-22T10:58:48.973 回答
0

If you create a block in your lambda empression you must use the return statement (if the lambda defines a result type).

If you just want the first element you can use FirstOrDefault instead of Where.

Result = ListOfNumbers.FirstOrDefault(val => val != Num1 && val != Num2 );

with a block:

Result = ListOfNumbers.FirstOrDefault(val => 
            { 
               var b = val != Num1 && val != Num2; 
               return b;
            } 
         );

I used && but I really don't know what is your condition...

于 2012-06-22T11:00:39.023 回答