Sort a list from another list IDs

匿名 (未验证) 提交于 2019-12-03 02:13:02

问题:

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?

回答1:

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


回答2:

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.



回答3:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!