Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement nested for loop into Linq?

Tags:

c#

asp.net

linq

How to convert following nested for loop into 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;
}
like image 978
Samiey Mehdi Avatar asked Jun 11 '26 08:06

Samiey Mehdi


2 Answers

Check out the related post: How do you perform a CROSS JOIN with LINQ to SQL?.

You could achieve this in the following way:

string result = string.Join("<br>", 
                    from username in names
                    from rolename in roles
                    where IsUserInRole(username, rolename)
                    select username + ":" + rolename);
like image 117
Igor Ševo Avatar answered Jun 12 '26 22:06

Igor Ševo


Off the top of my head (not tested):

var result = string.Join("<br>",names.SelectMany(n =>
       roles.Where(r => IsUserInRole(n, r)).Select(r => n + " : " + r))):
like image 31
Moeri Avatar answered Jun 12 '26 22:06

Moeri