Sudheer
Sudheer

Reputation: 71

Can these for loops be refactored in LINQ?

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        for (int k = 0; k < 10; k++)
        {

           string test = i.toString() + j.ToString() + k.ToString()
           list.add(test)
        }
    }
}

I am trying to iterate 3 variables in a loop to get multiple string values and add them to a list. My question: Is there a way in linq to make these loops in a single line? It might be a basic question, but I am new to this and I have gone through documentation and I am confused right now.

Upvotes: 1

Views: 101

Answers (2)

Yehor Androsov
Yehor Androsov

Reputation: 6152

Other answer is nice in terms of readability, but this one is closer of terms of stucture: loops over i, j, k variables

var list = Enumerable.Range(0, 10)
                .SelectMany(i => Enumerable.Range(0, 10)
                                .SelectMany(j => Enumerable.Range(0, 10)
                                        .Select(k => i.ToString() + j.ToString() + k.ToString())))
                .ToList();

Upvotes: 3

SomeBody
SomeBody

Reputation: 8743

Create an IEnumerable which goes from 0 to 999. Convert each of its elements to a string with three digits and finally convert it into a list:

List<string> list = Enumerable.Range(0,1000).Select(x => x.ToString("000")).ToList();

Online demo: https://dotnetfiddle.net/Qnsrlq

Upvotes: 3

Related Questions