Equivalent of FirstOrDefault with ranges

Lutger via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 1 23:56:07 PDT 2016


I was looking for something like FirstOrDefault* from .NET in 
phobos. For example, I have this piece of code:

string findBobOrReturnNull(string[] names)
{
     auto r = names.find("bob");
     if(r.empty) return null;
     return r.front;
}

assert(findBobOrReturnNull(["alice", "bob"]) == "bob");
assert(findBobOrReturnNull(["alice"]) is null);

How can I turn that into something like this, or is there another 
idiomatic way to write it as a single expression?

string findBobOrReturnNull(string[] names)
{
     return names.find("bob").firstOrDefault;
}

* 
https://msdn.microsoft.com/en-us/library/bb340482%28v=vs.110%29.aspx




More information about the Digitalmars-d-learn mailing list