LINQ way to check Contains in a List (regardless of white spaces)
我有以下代码检查UserRoles集合是否具有authorizedRolesList中的任何值。如果userrolename有空白,则不起作用。
最有效的处理方法是什么?
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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; } } } } |
参考文献:
我想最有效的LINQ方式意味着这里的可读性最高。
最明显的方法是在调用
1 | authorizedRolesList = AuthorizedRolesValues.Split(new []{','}, StringSplitOptions.RemoveEmptyEntries); |
但是,如果出于某种原因,您希望保留额外的空白或不能更改
1 | if (authorizedRolesList.Contains(userRoleName)) |
到
1 | if (authorizedRolesList.Any(x => x.Trim() == userRoleName)) |
顺便说一句,说到LINQ:
您可以用替换代码
1 | bool isAuthorizedRole = userRoles.Any(ur => authorizedRolesList.Any(ar => ar.Trim() == ur.Trim())) |
如果您确保
更具可读性的imho应该是
1 | bool isAuthorizedRole = userRoles.Intersect(authorizedRolesList, new IgnoreWhitespaceStringComparer()).Any(); |
其中
1 2 3 4 5 6 7 8 9 10 11 12 | 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 2 3 4 5 6 7 8 9 10 11 | 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); |
只需修剪列表中的每个条目,如下所示:
1 | authorizedRolesList.ForEach(a => a = a.Trim()); |
只需这样做:在拆分字符串时删除空白,然后使用trim()。
1 2 3 4 5 6 7 8 9 10 | 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()。
1 2 3 4 5 | //Contains Check if (authorizedRolesList.Contains(userRoleName.Trim())) { isAuthorizedRole = true; } |
试试这个
1 | bool ifExists = userRoles.Any(AuthorizedRolesValues.Split(',').Select(val => val = val.trim()); |
同样修剪原始列表如何?