Sort a list from another list IDs

c# sort two lists together
sort list using another list c#
c# sort list of lists
c# sort list of objects by multiple properties
python sort list by another list
c# sort list of ints
c# sort list<string with numbers
c# list sort lambda

I have a list with some identifiers like this:

List<long> docIds = new List<long>() { 6, 1, 4, 7, 2 };

Morover, I have another list of <T> items, which are represented by the ids described above.

List<T> docs = GetDocsFromDb(...)

I need to keep the same order in both collections, so that the items in List<T> must be in the same position than in the first one (due to search engine scoring reasons). And this process cannot be done in the GetDocsFromDb() function.

If necessary, it's possible to change the second list into some other structure (Dictionary<long, T> for example), but I'd prefer not to change it.

Is there any simple and efficient way to do this "ordenation depending on some IDs" with LINQ?

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

Order a List based on values in another List - MSDN, In order to sort a collection of objects based on another list that contains the proper order, we can create an extension method that performs a Join between these two collections and pass a func as innerKeySelector argument to allow us to sort this collection based on whatever key we want. Unless the lists involved are very long, I would use this solution, but here is an alternative solution that has time complexity O(n).Any solution using a Comparator together with Collections.sort or Arrays.sort has time complexity no better than O(n log n).

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.

C#: Sort one collection based on another one – Paris Polyzos' blog, List<Person> people = new List<Person>();. people. var sorted = people. // add another person that is not part of the displaySeq array. Yes it does, but sometimes you need more specific sorting system than just alphabetical sort.. like: 123-2009/person1 325-1998/xy 655-2014/vvv If you want to sort the items by middle part of string, you simply have to implement a custom comparator and manually returning 0, 1 or -1.

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

      i => i,
      d => d.Id,
      (i, d) => d);

LINQ tip, Use lambda expressions and LINQ to sort elements in a List. Call the List.Sort method. 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.

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

C# Sort List With Lambda, Comparison Method, Both lists have the same size. I want to sort the floats, but if I do so, the elements of the first list will not correspond to the correct game objects� Here is an example of how to sort a list and then make the changes in another list according to the changes exactly made to first array list. This trick will never fails and ensures the mapping between the items in list. The size of both list must be same to use this trick.

Sorting a list according to the sorting of another one, When your LINQ list contains value from another list, how can you filter it? Wipfli shows you how to use the LINQ filter to simplify this process. When you use sort() methods on List<Id>s that contain both 15-character and 18-character IDs, IDs for the same record sort together in API version 35.0 and later. Example In the following example, the list has three elements.

LINQ filter: How to filter a list using another list with LINQ, mapOrder.js. /**. * Sort array of objects based on another array. */. function mapOrder (array, order, key) {. array.sort( function (a, b) {. var A = a[key], B = b[ key];. List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of this method as follows: Sort(IComparer<T>) Sort(Int32, Int32, IComparer

Order an array of objects based on another array order � GitHub, C# queries related to “cc# sort list with list if ids”. c# order list by another list � how to sort list in c# � cc# sort list with list if ids� Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let’s discuss certain ways to sort list according to other list order.

  • are you assured that every docId occurs exactly once in docs, what property will hold the Id or will a selector Func<T, long> be required?
  • Does the first list represent a "master list"? Another words, will the second list be a subset representing a portion (or the entirety) of the first list?
  • @Kaf thats why I upvoted too, does rely on knowing the document ID property is called Id. Its not specified in the question.
  • @BorjaLópez, a quick note. You mention efficiency in your question. IndexOf is perfectly acceptable for your example and nice and simple. If you had a lot of data my answer might be better suited.…
  • @DenysDenysenko Fantastic. Thanks so much; exactly what I was looking for.
  • does not work if you have elements in docs that do not have ids in the ordering list
  • Quite inefficient - IndexOf is being called for every element in the source collection and OrderBy has to order the elements. The solution by @Jodrell is much faster.
  • I used this solution and it worked. Just that, i had to make the method static and the class static.
  • That is the answer we are looking for
  • This just proves that Join is too difficult to understand since everyone agreed that rewriting it was easier.
  • why order after a zip?
  • Because Zip combines each index (into a Tuple) with the document in the same position in the corresponding list. Then the OrderBy sorts the Tuples by the index part and then the select digs our just the docs from the now ordered list.
  • but, the result of GetDocsFromDb is unordered so you'll be creating Tuples where Item1 is unrelated to Item2.
  • I think this will produce incorrect results since ordering performing uppon id and not the index.