Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting pair-set using LINQ

Tags:

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} } 
like image 231
user160677 Avatar asked Oct 26 '09 11:10

user160677


2 Answers

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; } 
like image 200
Alex Avatar answered Oct 12 '22 23:10

Alex


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] }  ); 
like image 27
tvanfosson Avatar answered Oct 12 '22 22:10

tvanfosson