When i have a list
IList<int> list = new List<int>(); list.Add(100); list.Add(200); list.Add(300); list.Add(400); list.Add(500);
What is the way to extract a pairs
Example : List elements {100,200,300,400,500} Expected Pair : { {100,200} ,{200,300} ,{300,400} ,{400,500} }
The most elegant way with LINQ: list.Zip(list.Skip(1), Tuple.Create)
A real-life example: This extension method takes a collection of points (Vector2
) and produces a collection of lines (PathSegment
) needed to 'join the dots'.
static IEnumerable<PathSegment> JoinTheDots(this IEnumerable<Vector2> dots) { var segments = dots.Zip(dots.Skip(1), (a,b) => new PathSegment(a, b)); return segments; }
This will give you an array of anonymous "pair" objects with A and B properties corresponding to the pair elements.
var pairs = list.Where( (e,i) => i < list.Count - 1 ) .Select( (e,i) => new { A = e, B = list[i+1] } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With