A coleague asked me to write a one-liner to replace the following method:
public static bool IsResourceAvailableToUser(IEnumerable<string> resourceRoles, IEnumerable<string> userRoles)
{
foreach (var userRole in userRoles)
foreach (var resourceRole in resourceRoles)
if (resourceRole == userRole)
return true;
return false;
}
Resharper and I came up with this:
public static bool IsResourceAvailableToUser(IEnumerable<string> resourceRoles, IEnumerable<string> userRoles)
{
return userRoles.Where(resourceRoles.Contains).Count() > 0;
}
Is there a better way?
Given LINQ, yes:
return userRoles.Intersect(resourceRoles).Any();
Note that aside from the use of Intersect
to turn it into O(m) + O(n) instead O(m * n), using Any
is more efficient than using Count() > 0
- you know the answer as soon as you've found the first match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With