Lambda表达式返回错误

4
这是我的代码:
SomeFunction(m => { 
    ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID); 
 })

它返回如下错误:

lambda表达式类型的System.Func<IEnumerable>中未返回值的所有代码路径

4个回答

13
假设您正在尝试返回那个.Where()查询的结果,您需要去掉大括号和分号:

假设您想要返回该.Where()查询的结果,则需要删除那些大括号和分号:

SomeFunction(m => ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID))
如果你把它们放那里,ViewData[...].Where() 将被视为语句而不是表达式,所以你最终得到的是一个 lambda 表达式,它没能在应该返回时返回,从而导致错误。
或者如果你坚持要把它们放在那里,你需要使用 return 关键字使语句真正返回:
SomeFunction(m =>
{
    return ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID);
})

太好了!我太粗心了。谢谢你! - Lulu

4
您可以将lambda的主体写成一个表达式:
SomeFunction(m => ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID))

或者作为语句:

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

1

只需做

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

0

关于您的代码库还有一些未解决的问题.. 我做出了一些猜测,我认为这是正确的答案:

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

这就是为什么:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接