如何实现嵌套for循环到Linq?

时间:2013-12-21 09:33:20

标签: c# asp.net linq

如何将以下嵌套的for循环转换为linq:

public string MX()
{
    string[] names = { "ali", "reza", "john" };
    string[] roles = { "admin", "user" };
    List<string> result = new List<string>();
    foreach (string username in names)
    {
        foreach (string rolename in roles)
        {
            if (IsUserInRole(username, rolename))
            {
                result.Add(username + " : " + rolename);
            }
        }
    }
    return string.Join("<br>" ,result);
}
public bool IsUserInRole(string username, string rolename)
{
    //code
    return true;
}

2 个答案:

答案 0 :(得分:6)

查看相关帖子:How do you perform a CROSS JOIN with LINQ to SQL?

您可以通过以下方式实现此目的:

string result = string.Join("<br>", 
                    from username in names
                    from rolename in roles
                    where IsUserInRole(username, rolename)
                    select username + ":" + rolename);

答案 1 :(得分:3)

脱离我的头顶(未经测试):

var result = string.Join("<br>",names.SelectMany(n =>
       roles.Where(r => IsUserInRole(n, r)).Select(r => n + " : " + r))):