Sort one list by another

前端 未结 7 1225
借酒劲吻你
借酒劲吻你 2020-12-02 05:59

I have 2 list objects, one is just a list of ints, the other is a list of objects but the objects has an ID property.

What i want to do is sort the list of objects b

相关标签:
7条回答
  • 2020-12-02 06:18

    Join is the best candidate if you want to match on the exact integer (if no match is found you get an empty sequence). If you want to merely get the sort order of the other list (and provided the number of elements in both lists are equal), you can use Zip.

    var result = objects.Zip(ints, (o, i) => new { o, i})
                        .OrderBy(x => x.i)
                        .Select(x => x.o);
    

    Pretty readable.

    0 讨论(0)
  • 2020-12-02 06:20

    One possible solution:

    myList = myList.OrderBy(x => Ids.IndexOf(x.Id)).ToList();
    

    Note: use this if you working with In-Memory lists, doesn't work for IQueryable type, as IQueryable does not contain a definition for IndexOf

    0 讨论(0)
  • 2020-12-02 06:24

    One way of doing it:

    List<int>  order = ....;
    List<Item> items = ....;
    
    Dictionary<int,Item> d = items.ToDictionary(x => x.ID);
    
    List<Item> ordered = order.Select(i => d[i]).ToList();
    
    0 讨论(0)
  • 2020-12-02 06:24

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

    0 讨论(0)
  • 2020-12-02 06:26

    Not an answer to this exact question, but if you have two arrays, there is an overload of Array.Sort that takes the array to sort, and an array to use as the 'key'

    https://msdn.microsoft.com/en-us/library/85y6y2d3.aspx

    Array.Sort Method (Array, Array)
    Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

    0 讨论(0)
  • 2020-12-02 06:26

    Here is an extension method which encapsulates Simon D.'s response for lists of any type.

    public static IEnumerable<TResult> SortBy<TResult, TKey>(this IEnumerable<TResult> sortItems,
                                                             IEnumerable<TKey> sortKeys,
                                                             Func<TResult, TKey> matchFunc)
    {
        return sortKeys.Join(sortItems,
                             k => k,
                             matchFunc,
                             (k, i) => i);
    }
    

    Usage is something like:

    var sorted = toSort.SortBy(sortKeys, i => i.Key);
    
    0 讨论(0)
提交回复
热议问题