2

I have a List of a List (a matrix, which is sent via web.api HTTP POST from matlab).

List<List<decimal>> mylist;

The size of the matrix is nxm, how can I swap those lists? i.e.

mylist[i][j] --> mylist[j][i]

In Matlab the operation would be mylist' or in mathematical context (transposing)

mylist^T 
rst
  • 2,510
  • 4
  • 21
  • 47
  • 3
    Anything tried? Sample lists and an expected result available? – Tim Schmelter Aug 18 '17 at 10:38
  • @TimSchmelter the expected result is in the question, @derloopkat not required, may be `mxn` (as in the question mentioned) – rst Aug 18 '17 at 10:50
  • 1
    @robert: well, then this is my answer: `mylist[i][j] = mylist[j][i]` – Tim Schmelter Aug 18 '17 at 10:53
  • @TimSchmelter that won't work and you know that. I think the question is clear enough, at least someone (AliAdlavaran) understood it right away – rst Aug 18 '17 at 10:57
  • 1
    I think this operation is called "transposing" - @RobertStettler so did I, I think Tim is trying to make questions understandable for _anyone_ (but I'm not going to judge if an example is really needed in this case) – C.Evenhuis Aug 18 '17 at 11:00
  • I added the terms and some more information. Thanks @C.Evenhuis – rst Aug 18 '17 at 11:03
  • I think array is more meaningful than list in your operation. You should keep your inner list in same in count. right? – vipin Aug 18 '17 at 11:05
  • @TimSchmelter as far as the accepted solution is concerned, yes. However: there is it reduced to linq, I don't think that should be a requirement. If you feel the urge to flag this question, go ahead. – rst Aug 18 '17 at 11:17

1 Answers1

2

You could use Linq to achieve that without for loop like this:

var swapedList = 
   mylist
   .SelectMany((l, i) => l.Select((d, j) => new { i, j, d }))
   .GroupBy(l=>l.j)
   .Select(l=>l.Select(ll=>ll.d).ToList());
   .ToList();

I hope to be helpful for you :)

Ali Adlavaran
  • 3,697
  • 2
  • 23
  • 47