2

I have got the following LINQ query and would like to know equivalent normal C# code for it.

int[] arrayMain = new int[6];

return (from i in Enumerable.Range(0, arrayMain.Length / 2)
       from c in ReturnArrayOfLengthTwo()
       select c).ToArray();

The output of this query is coming as an array of length 6. But I would like to know about ordering because ReturnArrayOfLengthTwo just selects two random locations from arrayMain and then creates and returns an array of length 2.

Thanks

2
  • By 'equivalent normal C# code', do you mean using extension methods? Commented Jun 1, 2013 at 4:48
  • No I just mean normal C# code using loops etc. (no linq). Thanks. Commented Jun 1, 2013 at 4:49

2 Answers 2

1

In very basic C# (no LINQ, generics, extension methods, etc.), it would look something like:

int[] arrayMain = new int[6];

// Filling the arrayMain with two elements, so increment i by 2
// arrayMain[0], arrayMain[1] (first loop)
// arrayMain[2], arrayMain[3] (second loop)
// arrayMain[4], arrayMain[5] (third loop)
for (int i = 0; i < arrayMain.Length - 1; i += 2)
{
    // Returns two elements to insert into the arrayMain array.
    int[] returnedArray = ReturnArrayOfLengthTwo();

    arrayMain[i] = returnedArray[0];
    arrayMain[i + 1] = returnedArray[1];
}

Simply put, the ReturnArrayOfLengthTwo obviously returns two elements to put into the array. Therefore, you only need to iterate over the loop 3 times instead of 6 in order to put all the required values into arrayMain.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks man ! both answers were fully helpful. thanks for your time.
1

Well it would be something like:

var list = new List<int>();

for (int i = 0; i <= arrayMain.Length / 2; i++)
    foreach (int j in ReturnArrayOfLengthTwo())
        list.Add(j);

return list.ToArray();

I hope I understood you correct.

3 Comments

Can we just write arrayMain.Length/2 instead of Enumerable.Range(0, arrayMain.Length/2) ? Ah actually we can't since its half array basically !
@VVV Sure, I've edited :) But it's going to be a for lopp. Also, I need to get some sleep :)
thanks man ! both answers were fully helpful. thanks for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.