Reputation: 73
I want to convert this:
class ObjectWithArray
{
int iSomeValue;
SubObject[] arrSubs;
}
ObjectWithArray objWithArr;
to this:
class ObjectWithoutArray
{
int iSomeValue;
SubObject sub;
}
ObjectWithoutArray[] objNoArr;
where each objNoArr would have the same iSomeValue that objWithArr had, but a single SubObject that was in objWithArr.arrSubs;
The first idea that comes to mind is simply looping through objWithArr.arrSubs and using the current SubObject to create a new ObjectWithoutArray and adding that new object to an array. But, I am wondering if there is any functionality in an existing framework to do this?
Also, how about simply breaking up ObjectWithArray objWithArr into ObjectWithArray[] arrObjWithArr where each arrObjectWithArr.arrSubs would contain only one SubObject from the original objWithArr?
Upvotes: 1
Views: 108
Reputation: 5551
You can do it pretty easily using 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;
}
}
Upvotes: 0
Reputation: 484
Something like this would probably work.
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;
}
}
Upvotes: 2