【问题标题】:Return a List<> from method [duplicate]从方法返回 List<> [重复]
【发布时间】:2018-12-03 13:24:21
【问题描述】:

我想从我的 ASP.NET API 调用中返回一个 List&lt;string&gt;。我收到下面的编译错误 - 但不确定如何解决它。

无法将类型 System.Linq.IQueryable&lt;&lt;anonymous type: string compname, int invoicenum, decimal? invoiceamt, System.DateTime? invoicedate, System.DateTime? invoicepaddate&gt;&gt; 隐式转换为 System.Collections.Generic.List&lt;ITD&gt;。存在显式转换(您是否缺少演员表?)

这是我的语法:

public IEnumerable<ITD> Get()
{
    List<ITD> result = new List<ITD>();
    XE entities = new XE();
    result = (from a in entities.Companies
              join b in entities.Invoices
              on a.compNumber equals b.compNumber
              select new
              {
                  compname = a.Company1,
                  invoicenum = b.InvoiceNum,
                  invoiceamt = b.InvoiceAmt,
                  invoicedate = b.InvoiceDueDate,
                  invoicepaddate = b.InvoicePaidDate
              });
    return result;
}

【问题讨论】:

  • 您的 LINQ 查询是否需要 ToList()

标签: c# .net linq


【解决方案1】:

您返回的是 IQueryableanonymous type,而不是 IEnumerable&lt;ITD&gt;。将您的代码更改为:

select new ITD

如果您仍然收到错误,可能是因为您无法投影到映射实体上,那么您需要创建一个具有来自 ITD 实体所需属性的 DTO 类,如下所示:

public class ITDDTO
{
    public string Company { get; set; }
    //And other properties
}

另外不要忘记在查询末尾添加.ToList()

【讨论】:

  • 哈哈 - 如此快速简单的修复,但我没有看到!谢谢你
【解决方案2】:

您的 LINQ 查询返回接口 IQueryable 的实例,但您的变量 resultList&lt;ITD&gt;,请尝试这样做:

List<ITD> result = new List<ITD>(/*Insert LINQ here*/)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2018-08-27
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多