Reputation: 2758
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
Upvotes: 2
Views: 142
Reputation: 20794
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
.
Upvotes: 1
Reputation: 15138
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.
Upvotes: 1