Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 比较两个字符串的数据,然后将匹配的数据保存到另一个字符串上_C#_Generics - Fatal编程技术网

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

C# 比较两个字符串的数据,然后将匹配的数据保存到另一个字符串上,c#,generics,C#,Generics,我有两个字符串,我想比较这两个字符串,然后保存匹配的数据。我可以通过使用foreach循环实现这一点,如下代码所示,但我不想使用它。我只是想知道其他可以使用的语法。下面是我在foreach的帮助下使用此方法实现的代码: //matching the string data with the help of foreach to get the result List<string> roles = Roles.GetRolesForUser().ToList(); RoleResp

我有两个字符串,我想比较这两个字符串,然后保存匹配的数据。我可以通过使用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的帮助下匹配字符串数据以获得结果
列表角色=角色。GetRolesForUser().ToList();
RoleResponse response=application.GetAuthorizedSecurityRoles();
foreach(角色中的字符串r)
{
foreach(responses.SecurityRoles中的字符串securityRole)
{
if(r==securityRole)
{
结果。添加(角色);
}
}
}
返回结果;
如何在不使用foreach的情况下在另一个字符串中获得匹配结果。这可以通过连接方法实现吗


谢谢

您可以用下面的代码替换您的
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()
List lstResponses=新列表
lstressers=responses.SecurityRoles
结果=(来自角色中的r)
在r等于securityRole上的lstreponses中连接securityRole
选择r.ToList()
请分享结果


如果你不想使用foreach循环,那么就使用RegExI。我看不出你问的问题和你发布的代码之间有什么联系。如果您“可以通过使用foreach循环来实现这一点”,那么如果您展示这个解决方案(即使您不喜欢它),那么我们将更好地了解您想要做什么以及它应该如何工作,这可能会有所帮助。那么也许我们可以帮你找到更好的方法。@Corek:为了更好地理解,我修改了我的问题。ThanksWell,使用
LINQ
可以编写类似于
return responses.SecurityRoles.Where(role==securityRole)的代码,但在后台仍将使用foreach。对不起,我的意思是
返回角色.Intersect(responses.SecurityRoles)-但是,
foreach
仍然是隐藏的。