【发布时间】:2012-12-06 12:31:32
【问题描述】:
我有以下代码来检查 userRoles 集合是否具有authorizedRolesList 中的任何值。如果 userRoleName 有空格,则它不起作用。
LINQ 最有效的处理方式是什么?
代码
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;
}
}
}
}
参考:
- 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?
【问题讨论】:
-
使用 Enumerable.Any
方法 -
下面的答案几乎涵盖了它,但是,如果字符串中间有空格(如“Role A”),那么 .Trim 将不起作用。它只删除字符串开头和结尾的空格。您可以使用 String.Replace(" ", "") 来处理这种情况。