如何将列表转换为IEnumerable? [英] how to convert list to IEnumerable?

查看:369
本文介绍了如何将列表转换为IEnumerable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following function in which should return an IEnumerable type?how do I convert list to IEnumerable? and return an empty 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;
}

错误:

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

Cannot implicty convert type 'System.Collections.Generic.List<....> to System.Collections.Generic.IEnumerable<.....>.An explicit conversion exists(are you missing a cast?)

推荐答案

问题不在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.

这篇关于如何将列表转换为IEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆