Lambda表达式返回错误

这是我的代码:

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

并返回此错误:

并非所有代码路径都返回System.Func类型的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 matcher) { Person anotherone = new Person(); matcher(anotherone); return new DataSet(); } } public class Person { public string LeaderID, UserID; } class Program { public static Dictionary ViewData; private static void SomeFunction(Func 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); }); }); } } }