Как объединить два списка различных объектов в один список путем объединения одного элемента из каждого списка? - PullRequest
0 голосов
/ 01 ноября 2019

Привет. Я пытаюсь объединить два списка с разными объектами.

[{"SaveValues":[{"id":1,"allposition":{"x":-0.015270888805389405,
"y":9.267399787902832},"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},
"allscale":{"x":1.0,"y":1.0},"linepos0":{"x":0.0,"y":0.0,"z":0.0},
"linepos1":{"x":0.0,"y":0.0,"z":0.0},"movetype":1}],

"NoteValues":[{"movenumber":1,"notemsg":"Added one"}]},
{"SaveValues":[{"id":1,"allposition":{"x":-0.015270888805389405,
"y":9.267399787902832},"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},
"allscale":{"x":1.0,"y":1.0},"linepos0":{"x":0.0,"y":0.0,"z":0.0},
"linepos1":{"x":0.0,"y":0.0,"z":0.0},"movetype":2},{"id":1,
"allposition":{"x":-0.02840942144393921,"y":6.721944808959961},
"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},
"allscale":{"x":1.0,"y":1.0},"linepos0":{"x":0.0,"y":0.0,"z":0.0},
"linepos1":{"x":0.0,"y":0.0,"z":0.0},"movetype":2}],
"NoteValues":[{"movenumber":2,"notemsg":"Added two"}]},
{"SaveValues":[{"id":1,"allposition":{"x":-0.015270888805389405,
"y":9.267399787902832},"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},
"allscale":{"x":1.0,"y":1.0},"linepos0":{"x":0.0,"y":0.0,"z":0.0},
"linepos1":{"x":0.0,"y":0.0,"z":0.0},"movetype":3},{"id":1,
"allposition":{"x":-0.02840942144393921,"y":6.721944808959961},
"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},"allscale":{"x":1.0,"y":1.0},
"linepos0":{"x":0.0,"y":0.0,"z":0.0},"linepos1":{"x":0.0,"y":0.0,"z":0.0},
"movetype":3},{"id":1,"allposition":{"x":-0.10085266828536987,
"y":4.49822473526001},"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},
"allscale":{"x":1.0,"y":1.0},
"linepos0":{"x":0.0,"y":0.0,"z":0.0},
"linepos1":{"x":0.0,"y":0.0,"z":0.0},"movetype":3}],"NoteValues":
[{"movenumber":3,"notemsg":"Added three"}]},{"SaveValues":
[{"id":1,"allposition":{"x":-0.015270888805389405,"y":9.267399787902832}
,"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},
"allscale":{"x":1.0,"y":1.0},

"linepos0":{"x":0.0,"y":0.0,"z":0.0},
"linepos1":{"x":0.0,"y":0.0,"z":0.0},"movetype":4},{"id":1,
"allposition":{"x":-0.02840942144393921,"y":6.721944808959961},
"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},"allscale":{"x":1.0,"y":1.0},"linepos0":{"x":0.0,"y":0.0,"z":0.0},
"linepos1":{"x":0.0,"y":0.0,"z":0.0},"movetype":4},{"id":1,"allposition"
:{"x":-0.10085266828536987,"y":4.49822473526001},
"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},
"allscale":{"x":1.0,"y":1.0},
"linepos0":{"x":0.0,"y":0.0,"z":0.0},"linepos1":{"x":0.0,"y":0.0,"z":0.0},
"movetype":4},{"id":1,"allposition":{"x":0.17862117290496827,"y":1.5408382415771485},
"allrotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0},"allscale":{"x":1.0,"y":1.0},
"linepos0":{"x":0.0,"y":0.0,"z":0.0},"linepos1":{"x":0.0,"y":0.0,"z":0.0},"movetype":4}],
"NoteValues":[{"movenumber":4,"notemsg":"Added four"}]}]

Класс указан ниже.

[System.Serializable]
public class PlayerHandler 
{
public int id; 
public Vector2 allposition;
public Quaternion allrotation;
public Vector2 allscale;

public Vector3 linepos0;
public Vector3 linepos1;
public int movetype;


public PlayerHandler(int ids,Vector2 allpos,Quaternion allrot,Vector2 allscal,Vector3 Line0,Vector3 Line1,int Moves)

{
    this.id = ids;
    this.allposition = allpos;
    this.allrotation = allrot;
    this.allscale = allscal;
    this.linepos0 = Line0;
    this.linepos1 = Line1;
    this.movetype = Moves;
}



}

[System.Serializable]
public class PlayerMovement
{
public int movenumber;
public string notemsg;

public PlayerMovement(int Movenum,string Note)
{
    this.movenumber = Movenum;
    this.notemsg = Note;

}

}

Теперь у меня есть два списка с соответствующими значениями.

List<PlayerHandler> SaveValuesDeserialize = new List<PlayerHandler>();
List<PlayerMovement> NoteValuesDeserialzeList = new List<PlayerMovement>();

Я хотел бы объединить два вышеупомянутых списка в третий список с 0-м элементом из NoteValuesDeserialzeList [0], его 1-м элементом из SaveValuesDeserialize [0], 2-м элементом из NoteValuesDeserialzeList [1], 3-м элементом из SaveValuesDeserialize[1] до суммирования всех значений.

Различные сомнения возникают. Каким будет объект вновь добавленного списка List<?>AllcombinedList =new List<?>();.

и каков будет счет, чтобы сложить новый список (объединенный счет двух списков)?

Ответы [ 2 ]

1 голос
/ 01 ноября 2019

Поскольку единственным предком PlayerHandler и PlayerMovement является объект, вы можете создать только список объектов:

List<object> AllcombinedList = new List<object>();

int count = Math.Min(SaveValuesDeserialize.Count, NoteValuesDeserialzeList.Count);
// Or raise an exception if SaveValuesDeserialize.Count != NoteValuesDeserialzeList.Count
// Or ask the user what to do with the rest if it can happen
// Else use count = SaveValuesDeserialize.Count for example if always same
for ( int index = 0; index < count; index++ )
{
  AllcombinedList.Add(NoteValuesDeserialzeList[index]);
  AllcombinedList.Add(SaveValuesDeserialize[index]);
}

Возможно, вы можете использовать список кортежей для достижения своей цели:

var AllcombinedList = new List<Tuple<PlayerHandler, PlayerMovement>>();

int count = Math.Min(SaveValuesDeserialize.Count, NoteValuesDeserialzeList.Count);
// Or raise an exception if SaveValuesDeserialize.Count != NoteValuesDeserialzeList.Count
// Or ask the user what to do with the rest if it can happen
// Else use count = SaveValuesDeserialize.Count for example if always same
for ( int index = 0; index < count; index++ )
{
  var item = new Tuple<PlayerMovement, PlayerHandler>(NoteValuesDeserialize[index],
                                                      SaveValuesDeserialzeList[index]);
  AllcombinedList.Add(item);
}

Или анонимные кортежи:

var AllcombinedList = new List<(PlayerHandler, PlayerMovement)>();

int count = Math.Min(SaveValuesDeserialize.Count, NoteValuesDeserialzeList.Count);
// Or raise an exception if SaveValuesDeserialize.Count != NoteValuesDeserialzeList.Count
// Or ask the user what to do with the rest if it can happen
// Else use count = SaveValuesDeserialize.Count for example if always same
for ( int index = 0; index < count; index++ )
{
  AllcombinedList.Add((NoteValuesDeserialize[index], SaveValuesDeserialzeList[index]));
}

Или вы можете создать класс, предлагающий набор текста и именование:

var AllcombinedList = new List<PlayerItem>();

int count = Math.Min(SaveValuesDeserialize.Count, NoteValuesDeserialzeList.Count);
// Or raise an exception if SaveValuesDeserialize.Count != NoteValuesDeserialzeList.Count
// Or ask the user what to do with the rest if it can happen
// Else use count = SaveValuesDeserialize.Count for example if always same
for ( int index = 0; index < count; index++ )
  AllcombinedList.Add(new PlayerItem
  {
    Movement = NoteValuesDeserialzeList[index],
    Handler = SaveValuesDeserialize[index]
  });

public class PlayerItem
{
  public PlayerMovement Movement { get; set; }
  public PlayerHandler Handler { get; set; }
}

Если вы хотите управлять дополнительными элементами, вы можете, например,сделать это:

int count = Math.Max(SaveValuesDeserialize.Count, NoteValuesDeserialzeList.Count);
for ( int index = 0; index < count; index++ )
{
  var movement = index < NoteValuesDeserialzeList.Count 
               ? NoteValuesDeserialzeList[index] 
               : null;
  var handler = index < SaveValuesDeserialize.Count 
              ? SaveValuesDeserialize[index] 
              : null;
  AllcombinedList.Add(new PlayerItem
  {
    Movement = movement,
    Handler = handler
  });
}

Вы должны сами решить, что делать с дополнительными элементами (когда один из счетчиков больше другого): ничего не делать, добавить другой как ноль или создать экземпляр по умолчанию.

0 голосов
/ 01 ноября 2019

Универсальный List<T> принимает только один тип T в своем определении. Поэтому в нем не может быть элементов разных типов, все должны быть одного типа.

Вы можете использовать class или struct для хранения и предоставления обоих типов данных, а затем использовать этот классили структура как тип T в общем определении List<T>. В качестве альтернативы вы можете использовать кортежи .

Если вам кажется, что этот подход слишком сложен, то вы можете использовать в качестве типа T для своего List<T> предка обоих PlayerHandlerи PlayerMovement, что Object.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...