可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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();