2

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;
}
i3arnon
  • 107,189
  • 32
  • 306
  • 333
Samiey Mehdi
  • 8,986
  • 18
  • 48
  • 62

2 Answers2

6

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);
Community
  • 1
  • 1
Igor Ševo
  • 5,339
  • 3
  • 31
  • 73
3

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))):
Samiey Mehdi
  • 8,986
  • 18
  • 48
  • 62
Moeri
  • 8,854
  • 5
  • 41
  • 53