-
Notifications
You must be signed in to change notification settings - Fork 87
/
NSDictionary+LinqExtensions.m
89 lines (78 loc) · 2.32 KB
/
NSDictionary+LinqExtensions.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// NSDictionary+LinqExtensions.m
// LinqToObjectiveC
//
// Created by Colin Eberhardt on 25/02/2013.
// Copyright (c) 2013 Colin Eberhardt. All rights reserved.
//
#import "NSDictionary+LinqExtensions.h"
@implementation NSDictionary (QueryExtension)
- (NSDictionary *)linq_where:(LINQKeyValueCondition)predicate
{
NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (predicate(key, obj)) {
[result setObject:obj forKey:key];
}
}];
return result;
}
- (NSDictionary *)linq_select:(LINQKeyValueSelector)selector
{
NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
id object = selector(key, obj);
if (!object)
object = [NSNull null];
[result setObject:object forKey:key];
}];
return result;
}
- (NSArray *)linq_toArray:(LINQKeyValueSelector)selector
{
NSMutableArray* result = [[NSMutableArray alloc] init];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
id object = selector(key, obj);
if (!object)
object = [NSNull null];
[result addObject:object];
}];
return result;
}
- (BOOL)linq_all:(LINQKeyValueCondition)condition
{
__block BOOL all = TRUE;
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (!condition(key, obj)){
all = FALSE;
*stop = TRUE;
}
}];
return all;
}
- (BOOL)linq_any:(LINQKeyValueCondition)condition
{
__block BOOL any = FALSE;
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (condition(key, obj)){
any = TRUE;
*stop = TRUE;
}
}];
return any;
}
- (NSUInteger)linq_count:(LINQKeyValueCondition)condition
{
return [self linq_where:condition].count;
}
- (NSDictionary *)linq_Merge:(NSDictionary *)dictionary
{
NSMutableDictionary* result = [[NSMutableDictionary alloc] initWithDictionary:self];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (![result objectForKey:key]) {
[result setObject:obj forKey:key];
}
}];
return result;
}
@end