Lambda 表达式返回错误

本文关键字:错误 返回 表达式 Lambda | 更新日期: 2023-09-27 18:36:19

这是我的代码:

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

它返回此错误:

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

Lambda 表达式返回错误

假设您尝试返回该.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);
})

您可以将 lambda 的主体编写为表达式:

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

或作为声明:

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

只需执行

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

关于你的代码库有几个悬而未决的问题.. 做疯狂的假设 我认为这是最严格的答案:

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