Lambda表达式返回错误(Lambda expression returning error)

2019-06-25 05:13发布

这是我的代码:

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

并返回此错误:

不是所有的代码路径在类型lambda表达式返回一个值System.Func<IEnumerable>

Answer 1:

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

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

如果你把它们放在那里, ViewData[...].Where()将被视为一个声明,而不是一种表达,所以你最终当它应该不返回拉姆达导致错误。

或者,如果你坚持把他们那里,你需要一个return关键字,这样的声明实际上返回:

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


Answer 2:

你可以写拉姆达的身体作为表达式:

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

或语句:

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


Answer 3:

简单地做

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


Answer 4:

有一对夫妇的有关你的代码开放的问题..做野生的假设,我认为这是分辩答案:

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


文章来源: Lambda expression returning error
标签: c# lambda