简体   繁体   中英

Linq, project elements from 2 lists

I have a class:

public class Composite
{
    int Width { get; set; }
    int Distance { get; set; }
}

And 2 lists:

var widths = new List<int>(new[] {0, 1, 2, 3, 4 } );
var distances = new List<int>(new[] { 5, 6, 7, 8, 9 });

I want to create 5 Composite instances by combining the width and distance using the same index in the source lists:

  • 0 & 5
  • 1 & 6
  • 2 & 7
  • 3 & 8
  • 4 & 9

I'm guessing some kind of join selecting into the composite but joined by the index of the source lists. Can anyone help please?

var composites = widths.Zip(distances, (w, d) => new Composite() { Width = w, Distance = d })
                       .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM