HOW TO IMPLEMENT NESTED FOR LOOP INTO LINQ?

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
 1372  View(s)
Ratings:
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;

    }

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How to implement nested for loop into Linq?

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!