[英]How do I group and then count a NSSet?
How do I tackle grouping the records in a Core Data entity and then counting them so I can find the group with the highest count? 如何处理在核心数据实体中对记录进行分组,然后对它们进行计数,以便可以找到计数最高的组?
I have a 'set' which has many 'legs' each of which has one 'winner'. 我有一个“设置”,其中包含许多“腿”,每个腿都有一个“获胜者”。 The question I am trying to answer is: Who has won the most legs.
我想回答的问题是:谁赢得了最多的支持。
Help is appreciated. 感谢帮助。 Oh, and happy new year!
哦,新年快乐!
Iterate through the set and count the 'legs' for each 'winner'. 遍历集合并为每个“获胜者”计算“腿数”。 Save the leg-counts in a dictionary:
将支腿数保存在字典中:
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];
}
}
Now you need to find the key in the new dictionary with the highest value. 现在,您需要在新字典中找到具有最高值的键。
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.