如何对 NSSet 进行分组和计数?

发布于 2024-10-09 18:10:24 字数 124 浏览 5 评论 0原文

如何对核心数据实体中的记录进行分组,然后对它们进行计数,以便找到计数最高的组?

我有一个“集合”,它有许多“腿”,每条腿都有一个“获胜者”。我想回答的问题是:谁赢得了最多的腿。

感谢帮助。哦,新年快乐!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余生再见 2024-10-16 18:10:24

迭代该组并计算每个“获胜者”的“腿”。将腿计数保存在字典中:

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];

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文