LINQ方式检查包含在List中(无论空格如何)

时间:2012-12-06 12:31:32

标签: c# linq

我有以下代码检查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;
                    }
                }

            }
        }

参考:

  1. When to use .First and when to use .FirstOrDefault with LINQ?
  2. Intersect with a custom IEqualityComparer using Linq
  3. Ignoring hyphen in case insensitive dictionary keys
  4. C#: splitting a string and not returning empty string
  5. When does IEnumerable.Any(Func) return a value?
  6. Is IEnumerable.Any faster than a for loop with a break?

6 个答案:

答案 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))

BTW,谈论LINQ:

您只需用

替换代码即可
bool isAuthorizedRole = userRoles.Any(ur => authorizedRolesList.Any(ar => ar.Trim() == ur.Trim()))

如果您确保userRolesauthorizedRolesList不是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());