devludo
devludo

Reputation: 123

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

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

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

BUT:

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.

Upvotes: 0

Views: 288

Answers (1)

sgmoore
sgmoore

Reputation: 16067

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();

Upvotes: 1

Related Questions