且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将列表转换为IEnumerable?

更新时间:2021-07-02 22:32:00

问题不在List<T>IEnumerable<T>的转换中.因为List<T>实现IEnumerable<T>.

Problem is not in convertation of List<T> to IEnumerable<T>. Becuase List<T> implements IEnumerable<T>.

您的问题是通用参数不同.您正在尝试将List<T1>转换为IEnumerable<T2>.其中:

Your problem is that generic parameters are different. You are trying to convert List<T1> to IEnumerable<T2>. Where:

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

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

Simplest solution will be mapping (either manual or automatic). Automatic mapping is very easy. Add Automapper nuget package. Place this line somewhere on application start:

Mapper.Initialize(cfg => cfg.CreateMap<tblSoftwareImageTestPlan, SoftwareImageTestPlan>());

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

And now your method will look like:

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

注意:在代码中records不能具有null值,否则在ToList()调用时将具有NullReferenceException.所以if..else块还是没用.

NOTE: In your code either records cannot have null value, or you will have NullReferenceException at ToList() call. So if..else block is useless anyway.