-1

I am writing a program where I need to swap values from nested list. Here is what I am looking for example:

Let's say I have a List<object[]> where these list contains two rows as below:

{"id1", "id2", "id3"}, {1,2,3}

Now I want to make it like below:

{"id1", 1}, {"id2", 2}, {"id3", 3}

How can I do that in C#? Hopefully I have cleared my point.

Jaydeep
  • 265
  • 5
  • 18

1 Answers1

3

With 2 input sequences, this can be treated as a "zip" operation:

List<object[]> list = new List<object[]>
{
    new object[] {"id1", "id2", "id3" },
    new object[] {1,2,3},
};
var rotated = Enumerable.Zip(list[0], list[1],
    (x, y) => new object[] { x, y }).ToList();

Note I would advise against using lots of object[] etc here. There's almost always a better way to represent the data.


With an arbitrary number of input sequences, this would need to be done as a "transpose" operation.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • This is applicable to two rows only but let's say I am having more rows. It's unknown piece actually. – Jaydeep Jan 25 '18 at 07:45
  • @Jaydeep so you're looking for a "transpose" method? – Marc Gravell Jan 25 '18 at 07:46
  • Yes I believe that's what I want to do. – Jaydeep Jan 25 '18 at 07:47
  • @Jaydeep it is much easier with rectangular data; `List` is jagged - meaning: there's no guarantee that each inner item is the same length, but ultimately it isn't very different: https://stackoverflow.com/questions/29483660/how-to-transpose-matrix, https://stackoverflow.com/questions/4456420/transpose-2d-array-that-exists-as-ienumerable-of-ienumerable https://stackoverflow.com/questions/1599542/transpose-a-collection etc – Marc Gravell Jan 25 '18 at 07:49
  • Thank you Marc, I believe below post is more useful(specially first answer) https://stackoverflow.com/questions/39484996/rotate-transposing-a-listliststring-using-linq-c-sharp – Jaydeep Jan 25 '18 at 07:56