tags:

views:

102

answers:

3

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} }
+8  A: 

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] }  );
tvanfosson
Thanks you very much
+5  A: 

You can use a for loop:

var pairs = new List<int[]>();
for(int i = 0; i < list.Length - 1; i++)
    pairs.Add(new [] {list[i], list[i + 1]);

You can also use LINQ, but it's uglier:

var pairs = list.Take(list.Count - 1).Select((n, i) => new [] { n, list[i + 1] });

EDIT: You can even do it on a raw IEnumerable, but it's much uglier:

var count = list.Count();
var pairs = list
 .SelectMany((n, i) => new [] { new { Index = i - 1, Value = n }, new { Index = i, Value = n } })
 .Where(ivp => ivp.Index >= 0 && ivp.Index < count - 1)    //We only want one copy of the first and last value
 .GroupBy(ivp => ivp.Index, (i, ivps) => ivps.Select(ivp => ivp.Value));
SLaks
Thank you very much
A: 

Off the top of my head and completely untested:

public static T Pairwise<T>(this IEnumerable<T> list)
{
    T last;
    bool firstTime = true;
    foreach(var item in list)
    {
        if(!firstTime) 
            return(Tuple.New(last, item));
        else 
            firstTime = false; 
        last = item;
    }
}
Benjol