无法隐式转换类型&#39; System.Collections.Generic.List&lt; <anonymous type =“”>&gt;&#39;到&#39; System.Collections.Generic.List <string>&#39;

时间:2017-05-14 08:25:11

标签: c# linq generics

我的代码应该检查两个条件并返回值但是当我尝试返回 q 时出现此错误

  

无法隐式转换类型&#39; System.Collections.Generic.List&lt;&lt;匿名类型:字符串名称,字符串文件&gt;&gt;&#39;到&#39; System.Collections.Generic.List&lt;串GT;

我尝试了所有内容,但没有任何工作也不知道设置List<string>或将其设置为List<EF_Model.PDF>,PDF是我模型中的DTO

这是我的代码

  internal List<string> Customers_File(int _id)
    {
        using (var Context = new EF_Model.CoolerEntities())
        {
            var q = from c in Context.Customers
                    where c.Id == _id &&
                    c.Ref_PDF != null
                    select new { c.PDF.Name, c.PDF.File };
            return q.ToList();
        }
    }

4 个答案:

答案 0 :(得分:1)

您必须将匿名对象转换为字符串表示形式。(注意我使用C#6.0功能 - 字符串插值,您可以使用先前版本中的string.Format替换它。 例如:

return q.Select(x=>$"Name = {x.PDF.Name} File = {c.PDF.File}").ToList();

答案 1 :(得分:0)

您已将返回类型声明为字符串,但返回一个包含两个属性的匿名对象列表。那不会奏效。如果要返回字符串,则需要为每个列表项创建单个字符串。如果要返回对象更改返回类型

答案 2 :(得分:0)

您收到此错误是因为您已将Customers_File定义为返回字符串列表。但是,您返回的列表q不符合该描述。

在您的查询中,当您执行

select new { c.PDF.Name, c.PDF.File };

..您正在制作Anonymous Type,并将其存储在集合q中。此类型有两个字段,显然 a string

一些可能的解决方案是:

  • 将您的方法更改为返回类型List<object>而不是List<string>(不推荐)。
  • 通过某种形式的序列化(JSON或XML)将您的对象转换为字符串。
  • 为此数据创建类或结构,并将方法的返回类型更改为List<dataClass>

答案 3 :(得分:0)

您需要使用属性

定义对象
public class PdfInfo
{
    public string Name{get;set;}
    public string File{get;set;}
}

从您的方法中返回它们的列表

internal List<PdfInfo> Customers_File(int _id)

最后投射到那些,取代匿名对象:

....
select new PdfInfo() { Name=c.PDF.Name, File = c.PDF.File };
相关问题