比较两个字符串的数据,然后将匹配的数据保存在另一个字符串上

本文关键字:字符串 数据 保存 存在 另一个 然后 两个 比较 | 更新日期: 2023-09-27 18:29:28

我有两个字符串,我想比较这两个字符串然后保存匹配的数据。我可以通过使用foreach循环来实现这一点,如下所示,但我不想使用它。我只想知道其他可以用于它的语法。下面是我在foreach的帮助下使用它来实现的代码:

//matching the string data with the help of foreach to get the result
List<string> roles = Roles.GetRolesForUser().ToList();
RoleResponse response = application.GetAuthorizedSecurityRoles();
foreach (string r in roles)
        {
            foreach (string securityRole in responses.SecurityRoles)
            {
                if (r == securityRole)
                {
                    result.Add(roles);
                }
            }
        }
return result;

如何在不使用foreach的情况下在另一个字符串中获得匹配结果。这可以通过join方法实现吗?

感谢

比较两个字符串的数据,然后将匹配的数据保存在另一个字符串上

您可以用下面的代码替换foreach循环

List<string> lstResponses = new List<string>
lstResponses = responses.SecurityRoles
result = (from r in roles
          join securityRole in lstResponses on r equals securityRole
          select r).ToList()

请分享结果

参考