在给定ID的有序列表的情况下对对象数组进行排序 [英] Sorting an Array of objects given an ordered list of ids

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

问题描述

我有一个对象@users的集合,每个对象都有其id属性.

I have a collection of objects @users, each having its id attribute.

@users = [#<User id:1>, #<User id:2>]

我也有一个ids的有序数组.

I also have an ordered Array of ids.

ids = [2,1]

¿是否有一种神奇的方法可以使用该ID列表对集合进行排序?如果可能,无需再次调用数据库.

¿Is there a magical way to sort the collection using that list of ids? Without making another call to the database, if possible.

谢谢!!!

推荐答案

尝试一下.首先,从id-> user建立反向映射.

Try this. First, build up a reverse mapping from id -> user.

ids_users = {}

@users.each {|user| ids_users[user.id] = user}

然后,使用ID顺序

ids.collect{ |id| ids_users[id] }

这篇关于在给定ID的有序列表的情况下对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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