c# - Lambda 表达式 LINQ 中的条件 SELECT

标签 c# linq lambda

如果有人可以就以下问题提供建议,我将不胜感激: 我需要根据不同的条件选择不同的值(在我的例子中是适配器),我尝试如下:

return this.WrappedEntity.human_screen.SelectMany(e => e).Select(e =>
                {
                    AHuman human = _unitOfWork.HumansRepo.GetById(e.human_uid.ToString());
                    if (e.vid_screen == "1" && human.Gender== Gender.Female)
                    {
                        return new SqlFemaleScreening(e);
                    }
                    else if (e.vid_screen == "1" && human.Gender== Gender.Male)
                    {
                        return new SqlMaleScreening(e);
                    }
                    else
                    {
                        return new SqlChildScreening(e);
                    }
                });

但我收到以下错误:

ERROR: Type arguments for method "System.Linq.Enumerable.SelectMany <TSource,TResult> (System.Collections.Generic.IEnumerable <TSource>, System.Func <TSource, int, System.Collections.Generic.IEnumerable <TResult>>) "should be defined for use. Try to clearly define the type arguments.

提前非常感谢!

最佳答案

问题是,由于您返回多种不同类型的对象,编译器不确定您在返回的枚举中期望的对象类型。通常,当您使用 SelectSelectMany 之类的东西时,编译器可以解决这个问题,因此您无需担心。在这种情况下,您需要担心告诉它它们应该是什么。

您的代码将更改为如下所示:

return this.WrappedEntity.human_screen.SelectMany(e => e).Select<TSource, TResult>(e =>
     {
         //Same code as before in here
     });

TSource 应该是 select 方法中 e 的类型。 TResult 应该是 SqlFemaleScreeningSqlMaleScreeningSqlChildScreening 的基类型。

关于c# - Lambda 表达式 LINQ 中的条件 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17610396/

相关文章:

c# - 用另一个键值列表减去一个键值列表

java - 使用并行流从两个字符串中查找匹配字符的第一个索引

C# 将 Action<int> 转换为 lambda

c# - xaml 中定义的 Silverlight 控件在运行时为空

linq - FirstOrDefault() 关闭 LINQ 与 FirstOrDefault() 与 Lambda?

c# - List <int>分成三份

java - 如何在同一个 `groupingBy` 中处理 `stream()` 的结果 List<T> 值?

python - 最后导入的文件会覆盖以前文件中的语句。指定导入变量的更好方法?

c# - NuGet 提要与 NuGet 服务器与 NuGet 画廊

c# - 使用 PageViewer 和 LayoutPagerAdapter 时的内存管理