我有一个包含模型对象列表的数组
模型对象具有属性名称,年龄,性别, 我的日期如下
user* user1.name = "Bob",
user1.age = "10",
user1.gender = "M",
user* user2.name = "Bob",
user2.age = "11",
user2.gender = "M",
user* user3.name = "Woz",
user3.age = "15",
user3.gender = "M",
user* user4.name = "Woz",
user4.age = "16",
user4.gender = "M",
现在我需要得到唯一的名字和较小的年龄。
user* user1.name = "Bob",
user1.age = "10",
user1.gender = "M",
user* user3.name = "Woz",
user3.age = "15",
user3.gender = "M",
获得上述结果的有效方法是什么?在此先感谢任何提示或帮助将不胜感激。
答案 0 :(得分:3)
您可以简单地迭代数组以查找最年轻的用户,将每个用户存储在按名称键入的字典中。迭代完数组后,只需将所有字典值作为数组获取;
-(NSArray*)getYoungestUniqueUsersFromArray:(NSArray*)users {
NSMutableDictionary* youngestUsersDict = [NSMutableDictionary new];
for (User* user in users) {
User* currentUser = youngestUsersDict[user.name];
if (currentUser == nil || user.age < currentUser.age) {
youngestUsersDict[user.name]=user;
}
}
NSArray* youngestUsers = [youngestUsersDict allValues];
return youngestUsers;
}
答案 1 :(得分:0)
@interface User : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, strong) NSString *gender;
@end
@implementation User
+ (instancetype)create:(NSString *)name gender:(NSString *)gender age:(int)age {
User *user = [[User alloc] init];
user.name = name;
user.gender = gender;
user.age = age;
return user;
}
- (BOOL)isEqual:(id)object {
if ([object isKindOfClass:[User class]]) {
return [[(User *)object name] isEqualToString:self.name];
}
return NO;
}
- (NSUInteger)hash {
return self.name.hash;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *users = @[[User create:@"Bob" gender:@"M" age:11],
[User create:@"Bob" gender:@"M" age:9],
[User create:@"Bob" gender:@"M" age:10],
[User create:@"Woz" gender:@"M" age:25],
[User create:@"Woz" gender:@"F" age:36],
[User create:@"Woz" gender:@"F" age:23]];
users = [users sortedArrayWithOptions:NSSortConcurrent usingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
User *a = obj1;
User *b = obj2;
NSComparisonResult nameResult = [a.name compare:b.name];
if (nameResult == NSOrderedSame) {
return a.age > b.age;
}
return nameResult;
}];
NSSet *unique = [NSSet setWithArray:users];
for (User *user in unique) {
NSLog(@"%@: %zd - %@", user.name, user.age, user.gender);
}
}