Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List sort based on another list

Tags:

c#

sorting

linq

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 list, for example;

public class OptionType {     public int ID { get; set; }     public int Ordering { get; set; } }  public class Option {     public int ID { get; set; }     public int Type_ID { get; set; } }    

Obviously I can do a simple sort on a list of OptionTypes by doing

types_list.OrderBy(x => x.Ordering); 

Question is though, how could I go about ordering an 'options_list' by utilising the 'Type_ID' on the object which would relate to the ordering of the types_list. As in something like (obviously this isn't valid - but hopefully you will get the idea!)

options_list.OrderBy(x => x.Type_ID == types_list.OrderBy(e => e.Ordering)); 
like image 618
dan richardson Avatar asked Aug 12 '10 16:08

dan richardson


People also ask

How do you sort a list on basis of another list?

Explained: zip the two list s. create a new, sorted list based on the zip using sorted() . using a list comprehension extract the first elements of each pair from the sorted, zipped list .


2 Answers

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; 
like image 119
Anthony Pegram Avatar answered Oct 05 '22 21:10

Anthony Pegram


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.

like image 40
Good Night Nerd Pride Avatar answered Oct 05 '22 21:10

Good Night Nerd Pride