On 6/20/21 8:59 PM, someone wrote:
I often need to iterate through a filtered collection (associative array) as following:

```d
string strComputerIDunwanted = "WS2"; /// associative array key to exclude

foreach (strComputerID, udtComputer; udtComputers) { /// ..remove!(a => a == strComputerIDunwanted) ... ?

    if (strComputerID != strComputerIDunwanted) {

       ...

    }

}
```

Is there a way to filter the collection at the foreach-level to avoid the inner if ?

Two options for byKey and byKeyValue:


import std;

void main() {
  auto aa = [ "WS2" : 42, "WS3" : 43 ];
  string strComputerIDunwanted = "WS2";
  foreach (key; aa.byKey.filter!(k => k != strComputerIDunwanted)) {
    writeln(key, ' ', aa[key]);
  }

  // 't' is the tuple of key and value
  foreach (t; aa.byKeyValue.filter!(t => t.key != strComputerIDunwanted)) {
    writeln(t.key, ' ', t.value);
  }
}

Ali

Reply via email to