這是我的代碼:Lambda表達式返回錯誤
SomeFunction(m => {
ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID);
})
並返回該錯誤:
並非所有的代碼路徑型System.Func<IEnumerable>
這是我的代碼:Lambda表達式返回錯誤
SomeFunction(m => {
ViewData["AllEmployees"].Where(c => c.LeaderID == m.UserID);
})
並返回該錯誤:
並非所有的代碼路徑型System.Func<IEnumerable>
的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);
})
根本就
SomeFunction(m => 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 => 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); });
});
}
}
}
完美!是我粗心大意。謝謝! – Lulu