[SalesForce] Alternative for lambda expressions in apex salesforce

I know that Salesforce does not support lambda expressions and query syntax (like in LINQ) queries in apex collections. But, It would be a nice feature for developers.

Has anyone tried implementing similar kind of thing in Apex ? I found this github link where someone tried this, but its too big a package to include in the project.

For example

List<Opportunity> opportunities = new List<Opportunity>();
opportunities = [SELECT Id, Amount, StageName from Opportunity LIMIT 49000];
List<Opportunity> hugeOpportunities = opportunities.Where(o => o.Amount > 40000);


List<Opportunity> opportunities = new List<Opportunity>();
opportunities = [SELECT Id, Amount, StageName from Opportunity LIMIT 49000];
List<Opportunity> hugeOpportunities = from o in opportunities 
                                      where o.Amount > 40000
                                      select o;

Also, I can see an idea here, but somehow it has not yet received the votes needed to get picked by Salesforce.

Does Salesforce have any plans to implement this in future. Features that would be very useful as a developer would be to have support for

  • Anonymous classes
  • Lambda expressions (similar to method syntax of LINQ in C#)
  • Query syntax (similar to query syntax of LINQ in C#)

Can someone please suggest me an alternative for this, using which I can query on the collections without having to worry about the CPU time limit?

Best Answer

Can't speak for Salesforce's future plans, but...

Filtering on the order of 10K - 100K records shouldn't end up being too time consuming.

If you're not filtering on a general list of records multiple times, then the best option is probably to just include your filter as part of your initial query.

Probably the closest thing that you'll find to what you're looking for (besides that Apex Lambdas package) is bluewolf-beyond's Selector project. Looks like it hasn't been touched in a few years.

Given a list of SObjects, you could (with this package),

// N.B. I don't actually have this package installed anywhere
// This is my best guess at how the syntax would look, given my limited time with the docs
List<Opportunity> filtered = (List<Opportunity>)(Select.Field.greaterThan(Opportunity.Amount, 40000).filter(oppsList));
Related Topic