---
title: "How to implement nested for loop into Linq?"  
description: "How to implement nested for loop into Linq?"  
author: "Manoj Bhatt"  
published: 2013-12-23  
updated: 2013-12-23  
canonical: https://www.mindstick.com/forum/1825/how-to-implement-nested-for-loop-into-linq  
category: "asp.net"  
tags: ["asp.net"]  
reading_time: 1 minute  

---

# How to implement nested for loop into Linq?

How to [convert](https://www.mindstick.com/forum/2093/configurationmanager-appsettings-convert-n-to-n-why) following [nested](https://www.mindstick.com/forum/45/itemcommand-event-in-nested-repeater-and-listview) [for loop](https://www.mindstick.com/forum/12568/android-for-loop-not-working-in-main-thread) into [linq](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries):

```
    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;    }
```

## Replies

### Reply by 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);
```


---

Original Source: https://www.mindstick.com/forum/1825/how-to-implement-nested-for-loop-into-linq

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
