将输出从linq查询转换为列表<>的问题在asp.net中

时间:2011-04-20 11:46:47

标签: 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>'  

任何人都可以帮助我吗?

感谢您的期待

2 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:1)

您的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)映射到SoftwareTitle

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

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