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

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.