0

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?

2
  • 1
    Check the article @ techbrij.com/linq-combine-multiple-lists-parallel-c , specially Zip extension.
    – Chandu
    Nov 28, 2014 at 20:57
  • That's really useful, thanks. Inevitably these things get more complicated and knowing how to combine more than 2 sources and mixing types is bound to be useful in the future.
    – nopskazoid
    Nov 28, 2014 at 21:33

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.