我有以下代码检查userRoles集合是否具有authorizedRolesList中的任何值。如果userRoleName具有空格,则它不起作用。
处理此问题的最有效LINQ
方式是什么?
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;
}
}
}
}
参考:
答案 0 :(得分:4)
我猜最有效的LINQ方式在这里意味着最可读。
显而易见的方法是在调用Split()
时使用StringSplitOptions.RemoveEmptyEntries
而不是首先存储空格。
authorizedRolesList = AuthorizedRolesValues.Split(new []{','}, StringSplitOptions.RemoveEmptyEntries);
但是,如果由于某种原因你想要保留额外的空格或无法更改authorizedRolesList
中的条目,您可以轻松地从
if
子句
if (authorizedRolesList.Contains(userRoleName))
到
if (authorizedRolesList.Any(x => x.Trim() == userRoleName))
您只需用
替换代码即可bool isAuthorizedRole = userRoles.Any(ur => authorizedRolesList.Any(ar => ar.Trim() == ur.Trim()))
如果您确保userRoles
且authorizedRolesList
不是null
(请改用空集合)。
更可读的恕我直言将是
bool isAuthorizedRole = userRoles.Intersect(authorizedRolesList, new IgnoreWhitespaceStringComparer()).Any();
IgnoreWhitespaceStringComparer
看起来像
class IgnoreWhitespaceStringComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return x.Trim().Equals(y.Trim());
}
public int GetHashCode(string obj)
{
return obj.Trim().GetHashCode();
}
}
答案 1 :(得分:1)
尝试这样在拆分字符串时删除空格并使用Trim()
List<string> authorizedRolesList = null;
string AuthorizedRolesValues = "A, B ,C,D";
if (!String.IsNullOrEmpty(AuthorizedRolesValues))
{
string[] separators = {","};
authorizedRolesList = new List<string>(
((AuthorizedRolesValues)
.Split(separators , StringSplitOptions.RemoveEmptyEntries))
.Select(x => x.Trim());
}
之后在下面的代码
中使用这样的Trim() //Contains Check
if (authorizedRolesList.Contains(userRoleName.Trim()))
{
isAuthorizedRole = true;
}
答案 2 :(得分:1)
只需修改列表中的每个条目:
authorizedRolesList.ForEach(a => a = a.Trim());
答案 3 :(得分:1)
string authorizedRolesValues = "A, B ,C,D";
var authorizedRolesList = authorizedRolesValues
.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(role => role.Trim());
var userRoles = new Collection<string> {"B "};
bool isAuthorizedRole = userRoles
.Select(roleName => roleName.Trim())
.Any(authorizedRolesList.Contains);
答案 4 :(得分:0)
如何修剪原始列表?
authorizedRolesList = new List<string>((AuthorizedRolesValues).Split(',').Select(x => x.Trim()));
答案 5 :(得分:0)
试试这个
bool ifExists = userRoles.Any(AuthorizedRolesValues.Split(',').Select(val => val = val.trim());