2012-10-26 89 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; 
    } 
} 
相关问题