从另一个列表 ID 对列表进行排序 [英] Sort a list from another list IDs

查看:20
本文介绍了从另一个列表 ID 对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含如下标识符的列表:

I have a list with some identifiers like this:

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

此外,我还有一个 <T> 项目列表,它们由上述 id 表示.

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

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

我需要在两个集合中保持相同的顺序,以便 List 中的项目必须与第一个中的项目位于相同的位置(由于搜索引擎评分的原因).而这个过程无法在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.

如有必要,可以将第二个列表更改为其他结构(例如Dictionary),但我不想更改它.

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.

是否有任何简单有效的方法可以使用 LINQ 执行此根据某些 ID 进行排序"?

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

这篇关于从另一个列表 ID 对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆