[英]How do i do the following using LINQ feature of C#?
I need help with the following statement to be converted to lambda statement how do i do it? 我需要以下语句的帮助,将其转换为lambda语句,该怎么办?
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
gList.Add(new G(this, new L(row, column), 0, 20, 30));
}
}
thanks for all the help!!! 感谢所有的帮助!
var gList = Enumerable.Range(0, rows)
.SelectMany(row =>
Enumerable.Range(0, columns)
.Select(column => new G(this, new L(row, column), 0, 20, 30)
)
).ToList() or .ToArray();
SelectMany will flatten the Enumerable returned from the Select into an IEnumerable. SelectMany将把Select返回的Enumerable展平为IEnumerable。
var gList = from row in Enumerable.Range(0, rows)
from col in Enumerable.Range(0, columns)
select new G(this, new L(row, col), 0, 20, 30)
My favourite for inline cartesians like this 我最喜欢这样的内联直角坐标系
List<G> gList = Enumerable.Range(0, rows)
.SelectMany(row => Enumerable.Range(0, columns)
.Select(col => new G(this, new L(row, col), 0, 20, 30)))
.ToList();
Give me the indexes, project each index to a new L
, project each L
to a new G
and assign the resulting sequence of objects to a list named gList
. 给我索引,将每个索引投影到一个新的
L
,将每个L
投影到一个新的G
并将对象的结果序列分配给名为gList
的列表。
var indexes = from row in Enumerable.Range(0, rows)
from column in Enumerable.Range(0, columns)
select new { Row = row, Column = column };
var ls = indexes.Select(index => new L(index.Row, index.Column));
var gs = ls.Select(l => new G(this, l, 0, 20, 30)).ToList();
var gList = gs.ToList();
Note that if gList
is an existing list that you want to add to you can replace the last line by 请注意,如果
gList
是要添加到的现有列表,则可以将最后一行替换为
gList.AddRange(gs);
It reads exactly like what it is doing. 它的读取与正在执行的操作完全相同。
As you can see from the other answers, using lambdas don't always result in cleaner code. 从其他答案中可以看出,使用lambda并不总是会产生更清晰的代码。 Unless you have a specific reason for using lambdas in this case, I would leave the for loops as is.
除非在这种情况下有使用lambda的特定原因,否则我将保留for循环。
Readability should be your primary concern, but I imagine using a normal for
loop might be slightly faster because you don't have the overhead of function calls, but the difference in most cases won't matter. 可读性应该是您的首要考虑因素,但是我想使用普通的
for
循环可能会稍快一些,因为您没有函数调用的开销,但是大多数情况下的区别并不重要。
Putting everything into one single expression would lead to terrible code. 将所有内容放到一个表达式中会导致糟糕的代码。 Why would you do that?
为什么要这么做? Does the following help: (untested, out of my head)
请问以下帮助:(未经测试,超出我的脑海)
public IEnumerable<L> GenerateLs(int rows, int columns)
{
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
yield return new L(row, column);
}
}
}
gList.Add(l => GenerateLs(rows,columns).Select(new G(this,l,0,20,30)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.