How to order list based on some id found in another list c#?

Viewed 40

I know there are plenty of question about this topic but none of them seems to solve my answer (or at least from what i have found) pardon me if this is a duplicate question.

I have a list that i gather from SQL containing two properties SequenceId and Relevant:

var sequenceList = await context.SequenceDB.Where(c => c.PeopleId == peopleId).Select(c => {
  SequenceId = c.SequenceId,
  Relevant = c.Relevant
}).OrderBy(c => c.Relevant).ToListAsync();

Then i have another list like so:

var secondList = await context.Activity.ToListAsync();

FYI

  • the second list has multiple properties (hence column in the database) and one of them is SequenceId pointing to that SequenceId in SequenceDB.

What i want is to order the secondList based on the order of GUID's in the sequenceList.

BUT:

  • I just need to order them NOT exclude them from the list. And i don't want to exclude any of the elements from secondList
  • The result will be a list of Activity with as first elements the ones from sequenceList and then the rest

If you think this is a duplicate question please point me to the right one and i'll delete this one.

It seems simple even though is not for me.

1 Answers

You can join the lists using an outer join, so something like this should work.

First, number each row in secondList so we can retain the order for items which don't match those in the sequenceList.

var indexedSecondList = secondList.Select((e, index) => new { e, index });

(from r in indexedSecondList 
join s in sequenceList on r.e.SequenceId equals s.SequenceId into tmp
from t in tmp.DefaultIfEmpty()
 
 orderby t != null ? 0 : 1 ,                            // Sort the entries that are in SequenceList first
         t != null ? t.Relevant : (System.Guid?) null , // Then sort by Relevant 
         r.index                                        // Finally sort by original order in secondList

 select r.e).ToList();
Related