Lambda表达式LINQ中的条件SELECT



如果有人能就以下方面提出建议,我将不胜感激:我需要根据不同的条件选择不同的值(在我的情况下是Adapters),我试过这样做:

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

但我得到以下错误:

错误:应定义方法"System.Linq.Enumerable.SelectMany <TSource,TResult> (System.Collections.Generic.IEnumerable <TSource>, System.Func <TSource, int, System.Collections.Generic.IEnumerable <TResult>>)"的类型参数以供使用。尝试清楚地定义类型参数。

提前感谢!

问题是,因为您返回了多种不同类型的对象,编译器不确定您在返回的可枚举对象中期望的对象类型。通常,当你使用像SelectSelectMany这样的东西时,编译器可以计算出来,所以你不需要担心。在这种情况下,你需要担心告诉它它们应该是什么。

您的代码将更改为:

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

TSource应该是选择方法中e的类型。TResult应该是SqlFemaleScreeningSqlMaleScreeningSqlChildScreening的基本类型。

SelectMany表达式的结果应该是IEnumerable<T>,例如
human_screen.SelectMany(e => e.Some_Collection)

最新更新