Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将包含数组成员变量的对象转换为对象数组?_C#_Arrays_Object - Fatal编程技术网

C# 如何将包含数组成员变量的对象转换为对象数组?

C# 如何将包含数组成员变量的对象转换为对象数组?,c#,arrays,object,C#,Arrays,Object,我想将其转换为: class ObjectWithArray { int iSomeValue; SubObject[] arrSubs; } ObjectWithArray objWithArr; 为此: class ObjectWithoutArray { int iSomeValue; SubObject sub; } ObjectWithoutArray[] objNoArr; 其中,每个objNoArr将具有与objWithArr相同的iSome

我想将其转换为:

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

ObjectWithArray objWithArr;
为此:

class ObjectWithoutArray
{
    int iSomeValue;
    SubObject sub;
}

ObjectWithoutArray[] objNoArr;
其中,每个objNoArr将具有与objWithArr相同的iSomeValue,但只有一个子对象位于objWithArr.arrSubs中

想到的第一个想法是简单地循环通过objWithArr.arrSubs,并使用当前子对象创建一个新对象,而不使用数组,并将该新对象添加到数组中。但是,我想知道在现有的框架中是否有任何功能可以做到这一点



另外,简单地将ObjectWithArray objWithArr分解为ObjectWithArray[]arObjectWithArr,其中每个arObjectWithArr.arrSubs只包含原始ObjJWithArr中的一个子对象如何?

类似的方法可能会奏效

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;
    }
}
class ObjectWithArray
{
int值;
子对象[]子对象;
ObjectWithArray(){}//为构造函数执行的任何操作
不带数组[]toNoArray()的公共对象{
ObjectWithoutArray[]retVal=新ObjectWithoutArray[arrSubs.length];
for(int i=0;i
使用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;
    }
}

离题了,但下次有人问我什么是矛盾修饰法,我肯定会提到
ObjectWithoutArray[]objNoArr。谢谢。为什么要这样做,特别是如果每个项目都将具有相同的
iSomeValue
?我正在尝试“按摩”对象,以便AutoMapper可以将其映射到不包含数组的其他对象(例如,ObjectWithoutArray)。映射到对象的对象稍后将根据子对象的值进行排序并过滤到特定子集。