2010-10-31 61 views
2

我是c#的新手,在將其分配給查詢後嘗試訪問IList時出現問題。這裏是我的代碼:將查詢從IList轉換爲對象

System.Collections.IList Invoices = 
    (from p in entities.InvoiceCards 
     where (p.CustomerCard.ID == CustomerID) 
     select new 
     { 
     InvoiceID = p.ID, 
     InvoiceDatetime = p.DateTime, 
     InvoiceTotal = (decimal) p.InvoiceTotal, 
     }).ToList(); 

// update the grid 
invoiceCardDataGridView.DataSource = Invoices; 

-----------這裏編譯器抱怨對象C?如何在不執行查詢的情況下訪問IList中的對象?我需要使用IList作爲數據源。什麼是更好的方法?請包括代碼

foreach (var c in Invoices) 
    InvoiceTotal += (decimal)c.InvoiceTotal; 
+0

的可能重複[訪問C#匿名類型的對象(http://stackoverflow.com/questions/713521/accessing-c-sharp-anonymous-type-objects) – nawfal 2014-06-28 07:55:18

回答

0

如果列表中包含匿名類型和foreach循環是比第一個代碼塊,你不能使用這種方式的另一種方法。

請看看this post,這可能有助於你的情況。

0

如果您絕對必須使用IList那麼您最好定義一個顯式類型而不是使用匿名類型。那麼當你需要使用它們時,你必須將IList的元素轉換爲明確的類型。

1

您在查詢中使用匿名類型的問題。 因此,當你得到這個匿名類型的IList並分配給一個數據源時,默認情況下你將失去它的類型。

當你想從你的代碼的另一部分的數據源中檢索它時,你必須將它轉換爲適當的類型。由於匿名類型是由編譯器生成的,因此您將無法對其進行強制轉換。

解決方案是創建包含該類的類(如果該類尚不存在)。

public class InvoicePart 
{ 
    public int InvoiceID {get; set} 
    public DateTime InvoiceDatetime {get; set} 
    public decimal InvoiceTotal {get; set} 
} 

現在,您可以修改您的查詢來獲取一個類型的列表

List<InvoicePart> Invoices = 
    (from p in entities.InvoiceCards 
     where (p.CustomerCard.ID == CustomerID) 
     select new InvoicePart 
     { 
     InvoiceID = p.ID, 
     InvoiceDatetime = p.DateTime, 
     InvoiceTotal = (decimal) p.InvoiceTotal, 
     }).ToList(); 

// update the grid 
invoiceCardDataGridView.DataSource = Invoices; 

,當你會得到你的數據,你將它轉換爲一個列表

List<InvoicePart> Invoices = (List<InvoicePart>)invoiceCardDataGridView.DataSource; 

foreach (InvoicePart c in Invoices) 
{ 
    invoiceTotal += c.InvoiceTotal; 
} 
+0

請注意這個關鍵句子:「我需要使用IList'作爲數據源。」我把它看作是一個強類型的'IList'版本,並不是一個選項(注意'IList '不是'IList')。 – jason 2010-10-31 14:04:35

+0

我注意到,我注意到他是c#的新手。所以我試着解釋一下替代使用IList – Zied 2010-10-31 16:39:43

+0

感謝Zied。這對我工作 – 2010-10-31 16:58:40

0

Zied有權關於解決這個問題的想法。但請注意,綁定到List<T>不是bidierctional(對列表的更改不會反映在網格中)。對於您需要使用BindingSource

List<InvoicePart> Invoices = 
    (from p in entities.InvoiceCards 
     where (p.CustomerCard.ID == CustomerID) 
     select ... 

// update the grid 
var bs = new BindingSource(); 
bs.DataSource = Invoices; 
invoiceCardDataGridView.DataSource = bs; 
+0

謝謝你們幫助。 – 2010-10-31 16:53:56

+0

沒問題。考慮提供幫助你的答案,並接受最能幫助你的答案(我的投票將轉到Zied) – 2010-10-31 17:20:45