Click here to Skip to main content
14,934,046 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm aware of existence of Array.Sort, but I'm afraid it's not working for Lists. My scenario:

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.
Updated 3-Mar-21 21:16pm
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.

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!
Try this:
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})

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

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)])

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900