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

SQLの「GROUP BY」をobject-Cで実装するには?

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

これは、あなたが求めていることを実行するための単純なアルゴリズムであり、データ セットを 1 回だけループします。

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 に答える