Is there something similar to LINQ in Objective-C?
There is an acticle comparing the Windows and Cocoa ways of doing this. Cocoa uses Key Paths And NSPredicate....
Cocoa is my Girlfriend
The short answer is that there is not an equivalent to Linq for Objective-C but you can fake it with a mix of SQLite, NSPredicate and CoreData calls in a wrapper class shaped to your liking. You'd probably be interested in the core data guide, the predicate guide, and this example code.
From the above predicate guide:
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee"
inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// assume salaryLimit defined as an NSNumber variable
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"salary > %@", salaryLimit];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
I created my own Linq-style API for Objective C, which is available on github. Your specific example would look something like this:
NSArray* results = [[[people where:^BOOL(id person) {
return [person id] == 1 && [person id] != 2;
}]
select:^id(id person) {
return [person name];
}]
sort];
I think specific to your example this would be the equivalent in Cocoa:
NSArray *people = /* array of people objects */
NSPredicate *pred = [NSPredicate predicateWithFormat:@"Id = 1 AND Id != 2"];
NSSortDescriptor *byName = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:[byName autorelease]];
NSArray *matches = [people filteredArrayUsingPredicate:pred];
NSArray *sortedMatches = [matches sortedArrayUsingDescriptors:descriptors];
NSArray *justNames = [sortedMatches valueForKey:@"Name"];
It's a little more verbose than the LINQ example and some of my lines could have been combined but to my eye this is easier to parse.