如果有人可以就以下问题提供建议,我将不胜感激: 我需要根据不同的条件选择不同的值(在我的例子中是适配器),我尝试如下:
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.
提前非常感谢!
最佳答案
问题是,由于您返回多种不同类型的对象,编译器不确定您在返回的枚举中期望的对象类型。通常,当您使用 Select
或 SelectMany
之类的东西时,编译器可以解决这个问题,因此您无需担心。在这种情况下,您需要担心告诉它它们应该是什么。
您的代码将更改为如下所示:
return this.WrappedEntity.human_screen.SelectMany(e => e).Select<TSource, TResult>(e =>
{
//Same code as before in here
});
TSource
应该是 select 方法中 e
的类型。 TResult
应该是 SqlFemaleScreening
、SqlMaleScreening
、SqlChildScreening
的基类型。
关于c# - Lambda 表达式 LINQ 中的条件 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17610396/