how to filter associative arrays with foreach ?

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 21 22:08:56 UTC 2021


On 6/21/21 5:00 PM, Elronnd wrote:
> On Monday, 21 June 2021 at 03:59:10 UTC, someone wrote:
>> Is there a way to filter the collection at the foreach-level to avoid 
>> the inner if ?
> 
> Here's how I would do it:
> 
> foreach (k, v; coll) {
>      if (k == unwanted) continue;
>      ...
> }
> 
> You still have an if, but the actual loop body doesn't have to be 
> nested, so it's easy to follow the control flow.

Alternatively (if you're ok with this sort of thing):

foreach (k, v; coll) if (k != unwanted) {
}

It's actually visually shorter than doing the filter.

And the benefit to using the if statement over the filter wrapper is 
that the compiler has to do a lot less work.

-Steve


More information about the Digitalmars-d-learn mailing list