如何通过 linq 对集合进行非常具体的排序
var ids = new int[] { 3, 2, 20, 1 };
var entities = categories.Where(entity => ids.Contains(entity.Id));
我必须按照与 ids 数组中完全相同的方式对实体进行排序。我怎样才能做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该可以解决问题(写掉我的头顶,所以可能有错误)
This should do the trick (written off the top of my head, so may have mistakes)
您可以将
OrderBy
与ids
中 Id 的索引一起使用。要从
ids
获取 Id 的索引,您可以创建 Id 到索引的映射。这样您就可以在几乎恒定的时间内查找索引,而不必每次都调用IndexOf
并遍历整个列表。像这样的事情:
You could use
OrderBy
with the index of the Ids inids
.To get the index of an Id from
ids
, you could create a map of Id to index. That way you can look up the index in almost constant time, instead of having to callIndexOf
and traverse the whole list each time.Something like this:
您可能会尝试这样做:
这仅适用于唯一元素,但查找工作量是恒定的。
You may have a go with this:
This works for unique elements only, but the lookup efford is constant.