Lambda expression returning error

2019-02-19 04:52发布

问题:

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>

回答1:

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);
})


回答2:

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); 
})


回答3:

Simply do

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


回答4:

There are a couple of open questions about your codebase.. doing wild assumptions i think this is the rigth answer:

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

and here is why:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace App
{
    public class DataSet
    {
    }

    public class someclass
    {
        public DataSet Where(Func<Person, Boolean> matcher)
        {
            Person anotherone = new Person();
            matcher(anotherone);
            return new DataSet();
        }
    }

    public class Person
    {
        public string LeaderID, UserID;
    }

    class Program
    {
        public static Dictionary<String, someclass> ViewData;

        private static void SomeFunction(Func<Person, DataSet> getDataSet)
        {
            Person thepersonofinterest = new Person();
            DataSet thesetiamusinghere = getDataSet(thepersonofinterest);
        }

    static void Main(string[] args)
    {
        SomeFunction(
            (m) =>
            {
                return ViewData["AllEmployees"].Where(
                       (c) => { return (c.LeaderID == m.UserID); });
            });
    }
    }
}


标签: c# lambda