Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression returning error

Tags:

c#

lambda

This is my code:

SomeFunction(m => { 
    ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID); 
 })

and it returns this error:

Not all code paths return a value in lambda expression of type System.Func<IEnumerable>

like image 238
Lulu Avatar asked Dec 01 '22 22:12

Lulu


2 Answers

Assuming you're trying to return the result of that .Where() query, you need to drop those braces and that semicolon:

SomeFunction(m => ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID))

If you put them there, ViewData[...].Where() will be treated as a statement and not an expression, so you end up with a lambda that doesn't return when it's supposed to, causing the error.

Or if you insist on putting them there, you need a return keyword so the statement actually returns:

SomeFunction(m =>
{
    return ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID);
})
like image 62
BoltClock Avatar answered Dec 04 '22 12:12

BoltClock


You can either write lambda's body as an expression:

SomeFunction(m => ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID))

or as a statement:

SomeFunction(m => { 
    return ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID); 
})
like image 28
Dmitrii Lobanov Avatar answered Dec 04 '22 12:12

Dmitrii Lobanov