两个不同对象的两个数组的并集 [英] Union of two array of two different Objects

查看:68
本文介绍了两个不同对象的两个数组的并集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个包含两个不同对象的数组

对象1:

 班级合作伙伴{var pImage:字符串?var pTimeStamp:NSDate?var pTitle:字符串?var ID:字符串?} 

对象2:

 类客户{var cImage:字符串?var cTimeStamp:NSDate?var cTitle:字符串?var ID:字符串?var isCustomer:布尔?} 

我想从这两个 array objects 中创建一个 array (以一种有效的方式),这样就不会<具有相同 ID ( cID,pID )的Strong> Partner 和 customer 对象应在新的 Array .这两个数组基于ID 基本上并.请帮忙.

这些对象存储在CoreData中,当我确实想要高于期望的结果时,我已经有两个对象数组

解决方案

超级聪明的方法是让Set为您完成所有工作.使这些对象采用具有ID属性的通用协议.为该协议定义相等性以表示具有相同的ID值.现在,如果您不关心顺序,则将数组强制为Sets并合并Sets.如果您确实关心订单,则必须改用NSOrderedSet.您可以在执行合并操作后强制返回到Array.

另一种方法(哑"方式)是循环遍历数组,构建一个字典,其键为ID值.像基于ID相等的集合一样,这可以防止您要避免的重复.这并不是低效率的,因为您只需循环访问每个数组一次,并且字典键的查找速度很快.构建字典后,请转换回数组.但是,除非再次采取其他措施,否则您将失去原始阵列顺序.

(但是,这两个答案都假设您愿意修改对象,以便它们甚至可以存在于公共集合中;就目前情况而言,它们是不相关的,因为它们是两个不相关的类型.)

I have two arrays of two different objects

object 1:

Class  partner {
    var pImage: String?
    var pTimeStamp: NSDate?
    var pTitle: String?
    var ID: String?
}

object 2:

Class  customer {
    var cImage: String?
    var cTimeStamp: NSDate?
    var cTitle: String?
    var ID: String?
    var isCustomer : Bool? 
}

I want to create an array (in a efficient way, of-course) out of these two array objects such that no partner and customer object with same ID (cID,pID) should repeat within new Array. Basically union of these two array based on IDs. Please do help.

EDIT: these objects are stored in CoreData and at the time I do want above desired result I have already two array of these object

解决方案

The super-clever way would be to make Set do all the work for you. Make these objects adopt a common protocol with an ID property. Define equality for that protocol to mean having the same ID value. Now, if you don't care about order, coerce the arrays to Sets and union the sets. If you do care about order, you'll have to use NSOrderedSet instead. You can coerce back to Array after performing the union operation.

The alternative (the "dumb" way) is to cycle thru the arrays, building a dictionary whose key is the ID value. Like the set based on ID equality, this prevents the repetition you're trying to avoid. It's not inefficient because you're only cycling once thru each array, and lookup of the dictionary key is fast. When you've built the dictionary, convert back to an array. Again, however, you're going to lose the original array order unless you take additional measures.

(Both these answers, however, assume that you're willing to modify your objects so that they can even live in a common collection; as things stand, they can't, as they are two unrelated types.)

这篇关于两个不同对象的两个数组的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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