Samiey Mehdi
Samiey Mehdi

Reputation: 9414

How to implement nested for loop into 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;
}

Upvotes: 2

Views: 130

Answers (2)

Moeri
Moeri

Reputation: 9294

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))):

Upvotes: 3

Igor Ševo
Igor Ševo

Reputation: 5495

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);

Upvotes: 6

Related Questions