Does Groovy have any methods (out-of-the-box) that resemble the DefaultIfEmpty or FirstOrDefault methods found in LINQ?
Does Groovy have any methods (out-of-the-box) that resemble the DefaultIfEmpty or FirstOrDefault methods found
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
DefaultIfEmptycan be covered by:FirstOrDefaultis trickier, as I believe it returns the default value for a given type if there is no first element in the list… However, in Groovy (as it stands), there’s no way of detecting the default type of the object (unless it is a native type)You could do:
It should be noticed however that the
elvis operator ?:works on Groovy truth, so if the element on the left of the operator evaluates to false in Groovy (whether it benull, an empty list or string, the number 0, etc) it will return the right hand side)It should also be noted that I am not a .NET expert, so may have the functionality of these two functions incorrect.