2017-03-08 44 views
0

我有一個網格/集合對象(我們稱之爲SELECT_RESULTS),它是IList,ICollection,IEnumberable的子集。如何迭代通過ICollection並追加額外的字段

SELECT_RESULTS填充了PL/SQL SELECT存儲過程的返回結果。

我有2個問題: 1)我無法訪問SELECT_RESULTS領域在我的foreach循環,並 2)我需要添加從LINQ SELECT派生另一個字段的值到這個基於集合的主鍵上SELECT_RESULTS集合的值。

這是我到目前爲止已經試過:

// get the list of potential CUST_NAME that will be appended 
var q = (from tableX in dbContext.CUSTOMER 
     where tableX.CUST_ID = 42 
     select new 
      { 
       tableX.CUST_ID 
       tableX.CUST_NAME 
     tableX.A_DATE 
     }); 

// trying to get results to know what type it's a collection of: 
var results = SELECT_RESULTS as CollectionOfPeople; 

// dilemma : item is an Object here, so I'm unable to access the 
// different field names in the collection :-(

foreach (var item in results) 
{ 
    // question1) how to find the matching row in the collection. 
    // I am unable to see item.ID. 
    // Only can see item.ToString, item.ToHashCode, and other Object stuff 

    var q1 = q.Where (x => x.CUST_ID == item.ID); 

// question 2) I need to Append the CUST_NAME into the collection 
// onto the row having matching CUST_ID == ID 
    ??? 
} 

回答

1

不幸的是,我不知道CollectionOfPeople是什麼。所以可能還有其他的選擇,比如使用接口和DTO。

要回答您的第一個問題,您需要將項目轉換爲已知類型。如果你知道這個類型,那麼你可以嘗試將它轉換爲該類型。

// If you know the type you could try something like this: 
foreach (People item in results) 
{ 
    var q1 = q.Where (x => x.CUST_ID == item.ID); 
} 

否則,你可以看看的動態對象的可能性。

foreach (var item in results) 
{ 
    // This compiles but it doesn't mean it is correct. 
    // A non-existing property will throw an exception. 
    int i = ((dynamic)item).ID; 
    var q1 = q.Where (x => x.CUST_ID == i); 
} 

至於問題2,爲什麼不使用DTO存儲您的信息?如果您有班級People,那麼您可以在那裏添加CUST_NAME。使事情變得更容易。匿名類型可能很有用,但在這種情況下,似乎你讓自己變得不容易。

如果您需要展開對象,則可以考慮使用expando對象。看看這裏:Creating a dynamic, extensible C# Expando Object