2011-04-20 23 views
0

我有如下定义一个软件标题类:问题与LINQ查询输出转换为List <>在asp.net

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>' 

任何人都可以帮助我吗?

感谢预期

+0

这与答案无关,但请注意您正在使用2个custRecords.InvoiceNumber创建对象。它看起来像你想要的:{custRecords.SoftwareTitle,custRecords.InvoiceNumber} – Blazes 2011-04-20 11:53:38

回答

2

我认为这个问题是要创建一个匿名类型:

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

和你正在试图建立SoftwareTitles的列表。我不是语法100%,但尝试使用:

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

select代码

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

是返回一个annonymous型。您不能将您的匿名类型放入List<SoftwareTitles>

两个解决方案:

1)如果你让使用var关键字

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

2编译器确定您的列表的类型,你可以选择一个annonymous型)映射到一个SoftwareTitle对象的Select

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

我猜你可能想做第二种方法。使用一个annonymous类型的列表只是作为一个函数的中间步骤而非常有用,因为你通常不能将它作为函数参数传递到别的地方。

相关问题