1

我有标题数组,作者。

------------------------
title      author
------------------------
A        a   
B        a
C        b
D        c
E        c
F        d
G        d
------------------------

如果我选择 * 按作者分组

-----------------
a        A, B
b        C
c        D, E
d        F,G

如何通过 object-C 实现 SQL 的“GROUP BY”?

4

2 回答 2

2

创建班级书籍

@interface Book : NSObject
@property(strong)NSString *title;
@property(strong)NSString *author;
@end

现在实现为:

//创建对象,标题和作者

Book *b1=[Book new];
[b1 setTitle:@"A"];[b1 setAuthor:@"a"];

Book *b2=[Book new];
[b2 setTitle:@"B"];[b2 setAuthor:@"a"];

Book *b3=[Book new];
[b3 setTitle:@"C"];[b3 setAuthor:@"b"];

Book *b4=[Book new];
[b4 setTitle:@"D"];[b4 setAuthor:@"c"];

Book *b5=[Book new];
[b5 setTitle:@"E"];[b5 setAuthor:@"c"];

Book *b6=[Book new];
[b6 setTitle:@"F"];[b6 setAuthor:@"d"];

Book *b7=[Book new];
[b7 setTitle:@"G"];[b7 setAuthor:@"d"];


NSArray *books=@[b1,b2,b3,b4,b5,b6,b7];

//your manipulation starts here
NSMutableArray *groupByAuthors=[NSMutableArray new];
for (Book *book in books) {
    if (![groupByAuthors containsObject:book.author]) {
        [groupByAuthors addObject:book.author];
    }
}


for (NSString *author in groupByAuthors) {
    NSMutableArray *titles=[NSMutableArray new];
    for (Book *book in books) {
        if ([book.author isEqualToString:author]) {
            [titles addObject:book.title];
        }
    }
    NSLog(@"Author: %@, Books: %@",author,titles);
}
于 2013-03-05T17:02:13.567 回答
0

这是一个简单的算法来做你所要求的,并且只在你的数据集中循环一次。

int main (int argc, const char * argv[])
{
    @autoreleasepool {

        NSArray *booksAndTitles = @[
            @[@"Book A1", @"Author A"],
            @[@"Book B" , @"Author B"],
            @[@"Book C" , @"Author C"],
            @[@"Book A2", @"Author A"],
            @[@"Book A3", @"Author A"],
            @[@"Book C" , @"Author C"],
            @[@"Book B" , @"Author B"]
        ];

        NSMutableDictionary *titlesByAuthor = [NSMutableDictionary dictionary];

        for (NSArray *pair in booksAndTitles) {

            NSString *title  = pair[0];
            NSString *author = pair[1];

            NSMutableArray *titles = titlesByAuthor[author];
            if (titles == nil) {
                titles = [NSMutableArray array];
                titlesByAuthor[author] = titles;
            }

            [titles addObject:title];
        }

        NSLog(@"%@",titlesByAuthor);
    }
    return 0;
}

输出如下:

 {
    "Author A" =     (
        "Book A1",
        "Book A2",
        "Book A3"
    );
    "Author B" =     (
        "Book B",
        "Book B"
    );
    "Author C" =     (
        "Book C",
        "Book C"
    );
}
于 2013-03-06T11:18:53.350 回答