将foreach循环转换为LINQ
本文关键字:LINQ 转换 循环 foreach | 更新日期: 2023-09-27 18:07:51
ModelBeams
为List<ModelBeam>
, linesPassingThroughBeamEndsInYDirection
为List<double>
。
如何使用LINQ
编写下面的foreach
循环?
foreach (var beam in ModelBeams)
{
linesPassingThroughBeamEndsInYDirection.Add(beam.ConnectivityLine.I.Y);
linesPassingThroughBeamEndsInYDirection.Add(beam.ConnectivityLine.J.Y);
}
您可以使用Linq选择这两个片段作为一个集合,然后使用SelectMany来"flatten"这个集合:
linesPassingThroughBeamEndsInYDirection.AddRange(
ModelBeams.SelectMany(beam => new [] {
beam.ConnectivityLine.I.Y,
beam.ConnectivityLine.J.Y}
));
类似于
linesPassingThroughBeamEndsInYDirection
.AddRange(ModelBeams.SelectMany(mb => new double[] {mb.ConnectivityLine.I.Y,
mb.ConnectivityLine.J.Y})
);
使用
ModelBeams.ForEach(mb =>
{
linesPassingThroughBeamEndsInYDirection.Add(mb.ConnectivityLine.I.Y);
linesPassingThroughBeamEndsInYDirection.Add(mb.ConnectivityLine.J.Y);
});