I have two generic list objects, in which one contains ids and ordering, and the other a bunch of ids with each id in the second list having an id reference to the first lis
I like Lambda syntax, so I came up with this equivalent. I can see how query syntax is cleaner for joins.
var orderedOptions = options_list
.Join(
types_list,
option => option.Type_ID,
type => type.ID,
(option, type) => new { Option = option, Type = type })
.OrderBy(x => x.Type.Ordering)
.Select(x => x.Option);
For a slight reduction (of what, I'm not sure), this creates the new object with just the Ordering property, instead of the entire Type class. Not much different here, but I had a large class with the sort data, and only need the sorting property. Don't know if it mattered, but it was clearer to read.
var orderedOptions = options_list
.Join(
types_list,
option => option.Type_ID,
type => type.ID,
(option, type) => new { Option = option, Ordering = type.Ordering })
.OrderBy(x => x.Ordering)
.Select(x => x.Option);
It looks like the query syntax lets you order within the initial query, while lambda requires ordering after the join creates the new object. Maybe they're really doing the same thing under the covers though: creating the joined object, to be sorted then selected.
List.FindIndex() is your friend when your working with small lists:
var orderedB = listB.OrderBy(b => listA.FindIndex(a => a.id == b.id));
Working example: https://dotnetfiddle.net/CpLeFU
As @goodeye pointed out in the comments, performance will be a nightmare on larger lists. Use the accepted answer in that case.
You should be able to use a join to produce your desired output. Example using query syntax.
var orderedOptions = from option in options_list
join type in types_list
on option.Type_ID equals type.ID
orderby type.Ordering
select option;