2012-10-26 92 views
1

我想這個轉換:如何將包含作爲數組的成員變量的對象轉換爲對象數組?

class ObjectWithArray 
{ 
    int iSomeValue; 
    SubObject[] arrSubs; 
} 

ObjectWithArray objWithArr; 

這樣:

class ObjectWithoutArray 
{ 
    int iSomeValue; 
    SubObject sub; 
} 

ObjectWithoutArray[] objNoArr; 

其中每個objNoArr將有objWithArr有同樣iSomeValue,但單一的子對象,這是在objWithArr.arrSubs;

想到的第一個想法是簡單地循環瀏覽objWithArr.arrSubs並使用當前的SubObject創建一個新的ObjectWithoutArray並將該新對象添加到數組中。但是,我想知道現有框架中是否有任何功能來執行此操作?


此外,如何簡單地分手ObjectWithArray objWithArr到ObjectWithArray [] arrObjWithArr其中每個arrObjectWithArr.arrSubs將包含從原來的objWithArr只有一個子對象?

+3

題外話,但下一次有人問我一個矛盾是什麼,我肯定會提'ObjectWithoutArray [] objNoArr;'。謝謝你。 –

+0

爲什麼你想要這樣做,特別是如果每​​件物品都具有相同的'iSomeValue'? – ean5533

+0

我試圖「按摩」對象,以便AutoMapper可以將其映射到不包含數組的其他對象(例如ObjectWithoutArray)。映射到的對象稍後將根據子對象的值進行排序並過濾爲特定的子集。 – Victor

回答

2

像這樣的東西可能會奏效。

class ObjectWithArray 
{ 
    int iSomeValue; 
    SubObject[] arrSubs; 

    ObjectWithArray(){} //whatever you do for constructor 


    public ObjectWithoutArray[] toNoArray(){ 
     ObjectWithoutArray[] retVal = new ObjectWithoutArray[arrSubs.length]; 

     for(int i = 0; i < arrSubs.length; i++){ 
      retVal[i] = new ObjectWithoutArray(this.iSomeValue, arrSubs[i]); 
     } 

     return retVal; 
    } 
} 

class ObjectWithoutArray 
{ 
    int iSomeValue; 
    SubObject sub; 

    public ObjectWithoutArray(int iSomeValue, SubObject sub){ 
     this.iSomeValue = iSomeValue; 
     this.sub = sub; 
    } 
} 
0

你可以使用LINQ做到這一點很容易地:

class ObjectWithArray 
{ 
    int iSomeValue; 
    SubObject[] arrSubs; 

    ObjectWithArray() { } //whatever you do for constructor 


    public ObjectWithoutArray[] toNoArray() 
    { 
     ObjectWithoutArray[] retVal = arrSubs.Select(sub => new ObjectWithoutArray(iSomeValue, sub)).ToArray(); 
     return retVal; 
    } 
} 
相關問題