I have following code that checks whether userRoles collection has any of the values in authorizedRolesList. It does not work if the userRoleName has a whitespace.
What is the most efficient LINQ way for handling this?
CODE
List<string> authorizedRolesList = null;
string AuthorizedRolesValues = "A, B ,C,D";
if (!String.IsNullOrEmpty(AuthorizedRolesValues))
{
authorizedRolesList = new List<string>((AuthorizedRolesValues).Split(','));
}
string userRoleName = String.Empty;
Collection<string> userRoles = new Collection<string>();
userRoles.Add("B ");
bool isAuthorizedRole = false;
if (userRoles != null)
{
foreach (string roleName in userRoles)
{
userRoleName = roleName.Trim();
if (authorizedRolesList != null)
{
//Contains Check
if (authorizedRolesList.Contains(userRoleName))
{
isAuthorizedRole = true;
}
}
}
}
REFERENCE:
- When to use .First and when to use .FirstOrDefault with LINQ?
- Intersect with a custom IEqualityComparer using Linq
- Ignoring hyphen in case insensitive dictionary keys
- C#: splitting a string and not returning empty string
- When does IEnumerable.Any(Func) return a value?
- Is IEnumerable.Any faster than a for loop with a break?
I guess most efficient LINQ way means most readable here.
The obvious way is to use
StringSplitOptions.RemoveEmptyEntrieswhen callingSplit()and not storing the whitespace in the first place.But if for some reason you want to keep the additional whitespace or can’t change the entries in
authorizedRolesList, you can easily change yourifclause fromto
BTW, talking about LINQ:
You could just replace your code with
if you ensure
userRolesandauthorizedRolesListare notnull(use an empty collection instead).Even more readable IMHO would be something like
where
IgnoreWhitespaceStringComparerwould look like