Sort a list based on another list

I have two common list objects in which one contains identifiers and order, and the other contains many identifiers with each identifier in the second list having a reference to the identifier for 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 make a simple look in the OptionTypes list by doing

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

The question, however, is how I can order "options_list" using "Type_ID" for an object that will relate to the ordering of list_types. Like in something like (obviously this is not true, but hopefully you get this idea!)

 options_list.OrderBy(x => x.Type_ID == types_list.OrderBy(e => e.Ordering)); 
+27
sorting c # linq
Aug 12 '10 at 16:55
source share
3 answers

You can use the compound to obtain the desired result. An example of 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; 
+34
Aug 12 '10 at 17:09
source share

List.FindIndex () is your friend if you work with small lists:

 var orderedB = listB.OrderBy(b => listA.FindIndex(a => a.id == b.id)); 

Working example: https://dotnetfiddle.net/CpLeFU

As MaxJ noted in the comments, performance will be a big nightmare on large lists. Use the accepted answer in this case.

+17
May 30 '16 at 16:03
source share

I like the Lambda syntax, so I came up with this equivalent. I 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 small reduction (which I'm not sure), this creates a new object with only the Ordering property, and not for the entire Type class. There is not much here, but I had a large class with sorting data, and I only need the sorting property. I don’t know if it was important, but it was easier 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 allows you to order in the original request, and the lambda requires ordering after the connection creates a new object. Perhaps they really do the same under covers: creating a merged object that will be sorted, then selected.

+9
Nov 28 '12 at 0:10
source share



All Articles