将foreach循环转换为LINQ

本文关键字:LINQ 转换 循环 foreach | 更新日期: 2023-09-27 18:07:51

ModelBeamsList<ModelBeam>, linesPassingThroughBeamEndsInYDirectionList<double>

如何使用LINQ编写下面的foreach循环?

foreach (var beam in ModelBeams)
{
    linesPassingThroughBeamEndsInYDirection.Add(beam.ConnectivityLine.I.Y);
    linesPassingThroughBeamEndsInYDirection.Add(beam.ConnectivityLine.J.Y);
}

将foreach循环转换为LINQ

您可以使用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);
});