Advertise with us

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;
    }
Last updated:12/23/2013 5:04:57 AM

1 Answers

Pravesh Singh
Pravesh Singh

Hi Manoj,


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

OR

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

Answer