【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.List<>'无法隐式转换类型“System.Collections.Generic.List<>”
【发布时间】:2018-08-14 10:24:42
【问题描述】:

我正在使用 VS 2017 开发我的 .NET 应用程序。我编写了以下代码来从 api 中的表中检索数据

[HttpGet]
[Route("Index")]
public IEnumerable<Strings> Index()
{
    var list = db.Strings.Select(x => new { x.Iid, x.Value, x.Description, x.Itype }).ToList();
    return list;
}

我收到以下错误:

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

铸造是如何可能的?我已将 IEnumerable 更改为 IList,但问题存在。我不想为此创建 ViewModel。

【问题讨论】:

  • 你的函数应该返回IEnumerable&lt;Strings&gt;,但你返回的是一个匿名对象的集合..
  • 这里的Strings是一个模型类。
  • 而不是.Select(x =&gt; new {...(匿名对象),使用.Select(x =&gt; new Strings {....

标签: c# linq asp.net-web-api


【解决方案1】:

您正在使用Select(x =&gt; new …) 创建一个匿名对象列表,然后尝试将其作为IEnumerable&lt;Strings&gt; 返回,这就是您收到错误的原因。

无论如何,您都不能从方法中返回匿名对象 (1),因此要么更改查询以返回 Strings 列表,要么使用中间对象来表示数据。

(1) 好吧,你可以,但不是可用的形式。

【讨论】:

    【解决方案2】:

    为什么不这样做:

    public IEnumerable<Strings> Index()
        {
            var list = db.Strings.AsEnumerable();
            return list;
        }
    

    或者如果您想投影到模型:

            public IEnumerable<Strings> Index()
        {
            var list = db.Strings.Select(x => new Strings { Iid = x.Iid, Itype = x.Itype, Description = x.Description, Value = x.Value } ).AsEnumerable();
            return list;
        }
    

    【讨论】:

    • 如果 db.Strings 是实体的集合,这当然是不必要的。我只是对 ToList 比较明确。
    猜你喜欢
    • 2015-12-07
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多