[英]C# code for equivalent LINQ query
I have got the following LINQ query and would like to know equivalent normal C# code for it.我有以下 LINQ 查询,并想知道它的等效普通 C# 代码。
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.这个查询的输出是一个长度为 6 的数组。但我想知道排序,因为 ReturnArrayOfLengthTwo 只是从 arrayMain 中选择两个随机位置,然后创建并返回一个长度为 2 的数组。
Thanks谢谢
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.我希望我理解你正确。
In very basic C# (no LINQ, generics, extension methods, etc.), it would look something like:在非常基本的 C# 中(没有 LINQ、泛型、扩展方法等),它看起来像:
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.简单地说,
ReturnArrayOfLengthTwo
显然返回两个元素放入数组。 Therefore, you only need to iterate over the loop 3 times instead of 6 in order to put all the required values into arrayMain
.因此,您只需遍历循环 3 次而不是 6 次,即可将所有需要的值放入
arrayMain
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.