如何处理对核心数据实体中的记录进行分组,然后对它们进行计数,以便找到计数最高的组?
我有一个“集合”,它有许多“腿”,每条腿都有一个“赢家”。我要回答的问题是:谁赢得了最多的腿。
帮助表示赞赏。哦,新年快乐!
遍历集合并计算每个“获胜者”的“腿”。将腿数保存在字典中:
NSMutableDictionary* legCount = [[NSMutableDictionary alloc] init];
NSNumber* count;
for (leg in legsSet) {
id winner = [leg objectForKey:@"winner"]; // assumes leg is a dictionary
if (count = [legCount objectForKey:winner]) {
[legCount setObject:[NSNumber numberWithInt:[count intValue]+1] forKey:winner];
} else {
[legCount setObject:[NSNumber numberWithInt:1] forKey:winner];
}
}
现在您需要在新字典中找到具有最高值的键。
id winner = [[legCount keysSortedByValueUsingComparator:^(id obj1, id obj2) {
if ([obj1 intValue] > [obj2 intValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 intValue] < [obj2 intValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}] lastObject];