Home > DeveloperSection > Forums > How to implement nested for loop into Linq?
Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    December-23-2013 2:41 AM

 ASP.Net ASP.Net 
Ratings:


 1 Reply(s)
 1077  View(s)
Rate this:

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;

    }



Pravesh Singh

Total Post:411

Points:2881
Posted on    December-23-2013 5:04 AM

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


Don't want to miss updates? Please click the below button!

Follow MindStick