如何将列表转换为 IEnumerable?

Rit*_*itz 7 .net c# ienumerable

我有以下函数,其中应该返回 IEnumerable 类型?如何将列表转换为 IEnumerable?并返回一个空的 IEnumerable?

public IEnumerable<SoftwareImageTestPlan> GetAssignedTestPlansForSPSI(int SoftwareProductID, int SoftwareImageID)
{
    var records = _entities.tblSoftwareImageTestPlans
        .Where(x => x.SoftwareProductID == SoftwareProductID && x.SoftwareImageID == SoftwareImageID)
        .ToList();

    if (records == null)
        return new List<SoftwareImageTestPlan>();
    else
        return records;
}
Run Code Online (Sandbox Code Playgroud)

错误:

无法将类型“System.Collections.Generic.List<....> 隐式转换为 System.Collections.Generic.IEnumerable<.....>。存在显式转换(您是否缺少演员表?)

错误

Dar*_*ren 5

您将返回两种不同的对象类型:

  • tblSoftwareImageTestPlan - 驻留在实体框架模型中
  • SoftwareImageTestPlan - 驻留在您的 Qlasr 架构模型中

因此,当您声明以下内容时:

return records;
Run Code Online (Sandbox Code Playgroud)

它会抱怨该records对象不是 type SoftwareImageTestPlan。因此,您需要转换records为新的List<SoftwareImageTestPlan>,您可以通过LINQ projection.

var records = (from entities in _entities.tblSoftwareImageTestPlans
               where entities.SoftwareProductID equals SoftwareProductID && entities.SoftwareImageID == SoftwareImageId
               select new SoftwareImageTestPlan
               {
                  SoftwareProductID = entities.SoftwareProductID,
                  SoftwareImageID = entities.SoftwareImageID
               }).ToList();
Run Code Online (Sandbox Code Playgroud)

然后您可以使用您的原始声明:

if (records == null)
    return new List<SoftwareImageTestPlan>();
else
    return records;
Run Code Online (Sandbox Code Playgroud)


Ser*_*kiy 5

问题不在于List<T>to 的转换IEnumerable<T>。因为List<T>执行IEnumerable<T>.

您的问题是通用参数不同。您正在尝试转换List<T1>IEnumerable<T2>. 在哪里:

  • T1是 QlasrService.EntityFramework.tblSoftwareImageTestPlan
  • T2是 QlasrService.Model.SchemaModels.LAP.SoftwareImageTestPlan

最简单的解决方案是映射(手动或自动)。自动映射非常容易。添加 Automapper nuget 包。将此行放在应用程序启动的某个位置:

Mapper.Initialize(cfg => cfg.CreateMap<tblSoftwareImageTestPlan, SoftwareImageTestPlan>());
Run Code Online (Sandbox Code Playgroud)

现在您的方法将如下所示:

public IEnumerable<SoftwareImageTestPlan> GetAssignedTestPlansForSPSI(
   int SoftwareProductID, int SoftwareImageID)
{
    var testPlans = from tp in _entities.tblSoftwareImageTestPlans
                    where tp.SoftwareProductID == SoftwareProductID && tp.SoftwareImageID == SoftwareImageID
                    select tp;

    return Mapper.Map<IEnumerable<SoftwareImageTestPlan>>(testPlans);
}
Run Code Online (Sandbox Code Playgroud)

注意:在您的代码中要么records不能具有null价值,要么您将NullReferenceExceptionToList()通话中具有价值。所以if..else无论如何块都是无用的。