14,920,094 members
See more:
I'm aware of existence of `Array.Sort`, but I'm afraid it's not working for Lists. My scenario:

C#
```List<List<int>> listA = new List<List<int>>();
List<int> listB = new List<int>(new int[] {3,1,2});

//populate lists with numbers
//example code so you don't have to do it yourself
List<int> a = new List<int>(new int[] {1,2,3});
List<int> b = new List<int>(new int[] {2,1,3});
List<int> c = new List<int>(new int[] {3,2,1});

Example input:

```listA   listB
1 2 3   3
2 1 3   1
3 2 1   2```

Expected output (listB sorted, while sorting associated listA (first dimension only)):

```listA   listB
2 1 3   1
3 2 1   2
1 2 3   3```

Is it possible to achieve it, or I have to refactor whole project?

What I have tried:

Things that i have mentioned in the message above.
Posted
Updated 3-Mar-21 21:16pm
v2
Gerry Schmitz 3-Mar-21 13:41pm

The "expected output" makes no sense. And you seem to imply there is some sort of relationship between "list A" and "list B" when there is no evidence.
BillWoodruff 3-Mar-21 15:35pm

You create 'listB, but we can't see what you do with it. Show the code that produces those outputs.

Solution 1

One way would be to create a map (dictionary in C#) between the values in listB and the position in listA. The map would have the (key, value) pairs: (3, 0), (1, 1), (2, 2)

You refer to listA as listA[map[listB[i]]][j]. Before sorting listB, running i from 0 to 2 will output listA in the original order. After sorting listB, this will output listA in the sorted order.
Maciej Los 4-Mar-21 3:33am

Very good idea!
A5!

Solution 2

Try this:
C#
```var result = listA
.Select((x, i) => new {Index = i, Value = x})
.Join(listB.Select((x, i) => new {Index = i, Value = x}),
la => la.Index,
lb => lb.Index,
(la, lb) => new {A = la, B = lb})
.OrderBy(x => x.B.Value)
.Select(x => new {LA = x.A.Value, LB = x.B.Value})
.ToList();```

Here is an implementation of what Daniel Pfeffer[^] mentioned:

C#
```Dictionary<int, int> indexer = listB
.Select((x, i) => new KeyValuePair<int, int>(i, x))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

var result2 = listA
.OrderBy(x => indexer[listA.IndexOf(x)])
.ToList();```
v4