将foreach循环转换为LINQ

时间:2014-06-10 13:01:54

标签: c# linq list

ModelBeamsList<ModelBeam>linesPassingThroughBeamEndsInYDirectionList<double>

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

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

3 个答案:

答案 0 :(得分:5)

您可以使用Linq选择两个部分作为集合,然后使用SelectMany“展平”该集合:

linesPassingThroughBeamEndsInYDirection.AddRange(
   ModelBeams.SelectMany(beam => new [] {
                                         beam.ConnectivityLine.I.Y, 
                                         beam.ConnectivityLine.J.Y}
                        ));

答案 1 :(得分:2)

类似的东西:

linesPassingThroughBeamEndsInYDirection
    .AddRange(ModelBeams.SelectMany(mb => new double[] {mb.ConnectivityLine.I.Y,
                                                       mb.ConnectivityLine.J.Y})
             );

应该做的伎俩。

答案 2 :(得分:0)

使用此:

ModelBeams.ForEach(mb => 
{
    linesPassingThroughBeamEndsInYDirection.Add(mb.ConnectivityLine.I.Y);
    linesPassingThroughBeamEndsInYDirection.Add(mb.ConnectivityLine.J.Y);
});