在 asp.net 中,输出从 LINQ 查询转换为列表<>时出现问题



我有一个软件标题类,定义如下:

public class SoftwareTitles
{
string softwareTitle;
string invoiceNumber;
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
    this.softwareTitle = softwareTitle;
    this.invoiceNumber = invoiceNumber;
}
public string InvoiceNumber
{
    get
    {
        return this.invoiceNumber;
    }
}
public string SoftwareTitle
{
    get
    {
        return this.softwareTitle;
    }
}

}

和我得到软件标题和发票号码从我的linq查询,我想在一个列表中存储使用以下代码:

   List<SoftwareTitles> softwareTitlesList = new List<SoftwareTitles>();
var result = (from CustomersRecord custRecords in custRecordContainer select new { InvoiceNumber = custRecords.InvoiceNumber, SoftwareTitle = custRecords.InvoiceNumber }).ToList();
        softwareTitlesList = result;

但是它给了我这个错误:

Error   1   Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<SoftwareTitles>'  

有人能帮我吗?

感谢期待

我认为问题在于您正在创建一个匿名类型:

select new { InvoiceNumber = custRecords.InvoiceNumber, SoftwareTitle = custRecords.InvoiceNumber }

,您正在尝试构建一个SoftwareTitles列表。我不是100%的语法,但尝试使用:

select new SoftwareTitle( custRecords.SoftwareTitle, custRecords.InvoiceNumber)

您的select代码

select new { 
       InvoiceNumber = custRecords.InvoiceNumber, 
       SoftwareTitle = custRecords.InvoiceNumber 
}

返回一个匿名类型。你不能把你的匿名类型放入List<SoftwareTitles>

两个解决方案:

1)如果您让编译器使用var关键字

确定列表的类型,则可以选择匿名类型
var myList = from CustomersRecord custRecords 
              in custRecordContainer 
               select new { 
                   InvoiceNumber = custRecords.InvoiceNumber, 
                   SoftwareTitle = custRecords.InvoiceNumber 
             }).ToList();

2)映射到Select中的SoftwareTitle对象

List<SoftwareTitle> myList = from CustomersRecord custRecords 
                              in custRecordContainer 
                               select new SoftwareTitle { 
                                  InvoiceNumber = custRecords.InvoiceNumber, 
                                  SoftwareTitle = custRecords.InvoiceNumber 
                               }).ToList();

我猜你可能想用第二种方法。使用匿名类型的列表仅在函数的中间步骤中真正有用,因为您通常不能将其作为函数参数传递到其他地方。

相关内容

  • 没有找到相关文章

最新更新