-1

I have two ILists (of different Types), a and b. They are the same size because every a.G.Id matches exactly one b.G.Id.

b is sorted (because of an OrderBy(b=>b.SortVal). Now I want to sort the list a. (Classical sorting algorithms would help if I would have an a.SortVal and would just sort a without the help of a second list but that's not the case).

thestruggleisreal
  • 940
  • 3
  • 10
  • 26

3 Answers3

1
var dic = a.ToDictionary(x => x.gId);

var aSorted = b.Select(x => dic[x.G.Id];

should do it

Basically creating a dictionary to identify a's items by their gId and then using it while looping through b's (sorted) items should return the items in a as ordered in b.

The dictionary is used to make lookups faster than a scan.

vc 74
  • 37,131
  • 7
  • 73
  • 89
0

You can do something like this:

a = a.OrderBy(x => b.FindIndex(b.G.Id == x.gId));

I've answered a question much like this one before - Sort a list by a custom order - but it's not an exact duplicate.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

I did .Include(x=>x.G) when initialising b. Then I defined and initialised a new list bIds=b.Select(b=>b.G.Id).ToList();

and

a = a.OrderBy(x => bIds.IndexOf(x.G.Id)).ToList();

did it.

(with the help of https://stackoverflow.com/a/15275394/10357604 )

thestruggleisreal
  • 940
  • 3
  • 10
  • 26