c# - Sort a list from another list IDs

ID : 20087

viewed : 7

Tags : c#linqsortingcollectionsc#

Top 5 Answer for c# - Sort a list from another list IDs

vote vote

92

docs = docs.OrderBy(d => docsIds.IndexOf(d.Id)).ToList(); 
vote vote

88

Since you don't specify T,

IEnumerable<T> OrderBySequence<T, TId>(        this IEnumerable<T> source,        IEnumerable<TId> order,        Func<T, TId> idSelector) {     var lookup = source.ToDictionary(idSelector, t => t);     foreach (var id in order)     {         yield return lookup[id];     } } 

Is a generic extension for what you want.

You could use the extension like this perhaps,

var orderDocs = docs.OrderBySequence(docIds, doc => doc.Id); 

A safer version might be

IEnumerable<T> OrderBySequence<T, TId>(        this IEnumerable<T> source,        IEnumerable<TId> order,        Func<T, TId> idSelector) {     var lookup = source.ToLookup(idSelector, t => t);     foreach (var id in order)     {         foreach (var t in lookup[id])         {            yield return t;         }     } } 

which will work if source does not zip exactly with order.

vote vote

71

Jodrell's answer is best, but actually he reimplemented System.Linq.Enumerable.Join. Join also uses Lookup and keeps ordering of source.

    docIds.Join(       docs,       i => i,       d => d.Id,       (i, d) => d); 
vote vote

65

One simple approach is to zip with the ordering sequence:

List<T> docs = GetDocsFromDb(...).Zip(docIds, Tuple.Create)                .OrderBy(x => x.Item2).Select(x => x.Item1).ToList(); 
vote vote

52

Top 3 video Explaining c# - Sort a list from another list IDs

Related QUESTION?