By Cristi Diaconescu


2010-12-16 13:45:23 8 Comments

var nums = new[]{ 1, 2, 3, 4, 5, 6, 7};
var pairs  = /* some linq magic here*/ ;

=> pairs = { {1, 2}, {3, 4}, {5, 6}, {7, 0} }

The elements of pairs should be either two-element lists, or instances of some anonymous class with two fields, something like new {First = 1, Second = 2}.

12 comments

@Catalin 2019-06-17 16:36:15

Another simple solution using index and index + 1.

var nums = Enumerable.Range(1, 10);
var pairs = nums.Select((item, index) =>
  new { First = item, Second = nums.ElementAtOrDefault(index + 1) })
    .SkipLastN(1);

pairs.ToList().ForEach(p => Console.WriteLine($"({p.First}, {p.Second}) "));

Last item is invalid and must be removed with SkipLastN().

@Rax 2018-12-03 11:09:54

Another option is to use the SelectMany LINQ method. This is more for those who wish to iterate through a list of items and for each item return 2 or more of it's properties. No need to loop through the list again for each property, just once.

var list = new [] {//Some list of objects with multiple properties};

//Select as many properties from each Item as required. 
IEnumerable<string> flatList = list.SelectMany(i=> new[]{i.NameA,i.NameB,i.NameC});

@Cristi Diaconescu 2018-12-04 14:48:05

Thanks for the answer, but this gets properties from each item and flattens them into a single list. That's not what the original question was about.

@kalisohn 2016-07-28 16:33:08

IList<int> numbers = new List<int> {1, 2, 3, 4, 5, 6, 7};
var grouped = numbers.GroupBy(num =>
{
   if (numbers.IndexOf(num) % 2 == 0)
   {
      return numbers.IndexOf(num) + 1;
   }
   return numbers.IndexOf(num);
});

If you need the last pair filled with zero you could just add it before doing the grouping if the listcount is odd.

if (numbers.Count() % 2 == 1)
{
   numbers.Add(0);
}

Another approach could be:

var groupedIt = numbers
   .Zip(numbers.Skip(1).Concat(new[]{0}), Tuple.Create)
   .Where((x,i) => i % 2 == 0);

Or you use MoreLinq that has a lot of useful extensions:

IList<int> numbers = new List<int> {1, 2, 3, 4, 5, 6, 7};
var batched = numbers.Batch(2);

@Craig Gidney 2010-12-16 14:47:46

None of the default linq methods can do this lazily and with a single scan. Zipping the sequence with itself does 2 scans and grouping is not entirely lazy. Your best bet is to implement it directly:

public static IEnumerable<T[]> Partition<T>(this IEnumerable<T> sequence, int partitionSize) {
    Contract.Requires(sequence != null)
    Contract.Requires(partitionSize > 0)

    var buffer = new T[partitionSize];
    var n = 0;
    foreach (var item in sequence) {
        buffer[n] = item;
        n += 1;
        if (n == partitionSize) {
            yield return buffer;
            buffer = new T[partitionSize];
            n = 0;
        }
    }
    //partial leftovers
    if (n > 0) yield return buffer;
}

@Cristi Diaconescu 2010-12-16 15:08:33

Looking at all the answers, it does seem that Linq is not the best approach here. Your implementation is pretty clean.

@Hamish Grubijan 2012-06-28 00:03:37

It should be public static IEnumerable<T[]> Partition<T>....

@Handcraftsman 2010-12-17 14:48:28

public static IEnumerable<List<T>> InSetsOf<T>(this IEnumerable<T> source, int max)
{
    return InSetsOf(source, max, false, default(T));
}

public static IEnumerable<List<T>> InSetsOf<T>(this IEnumerable<T> source, int max, bool fill, T fillValue)
{
    var toReturn = new List<T>(max);
    foreach (var item in source)
    {
        toReturn.Add(item);
        if (toReturn.Count == max)
        {
            yield return toReturn;
            toReturn = new List<T>(max);
        }
    }
    if (toReturn.Any())
    {
        if (fill)
        {
            toReturn.AddRange(Enumerable.Repeat(fillValue, max-toReturn.Count));
        }
        yield return toReturn;
    }
}

usage:

var pairs = nums.InSetsOf(2, true, 0).ToArray();

@Jahan Zinedine 2010-12-16 13:51:54

 var nums = new float[] { 1, 2, 3, 4, 5, 6, 7 };
 var enumerable = 
        Enumerable
          .Range(0, nums.Length)
          .Where(i => i % 2 == 0)
          .Select(i => 
             new { F = nums[i], S = i == nums.Length - 1 ? 0 : nums[i + 1] });

@Lasse Vågsæther Karlsen 2010-12-16 13:57:09

-1: That's not what he asked for.

@Yakimych 2010-12-16 14:25:01

That will return pairs as {{1,2}, {2,3}, ...}

@Jahan Zinedine 2010-12-16 16:22:51

@Lasse It works fine as I understand the question so please revoke your downvote

@Ali Tarhini 2010-12-16 13:58:28

this gives all possible pairs(vb.net):

Dim nums() = {1, 2, 3, 4, 5, 6, 7}
Dim pairs = From a In nums, b In nums Where a <> b Select a, b

Edit:

 Dim allpairs = From a In nums, b In nums Where b - a = 1 Select a, b
 Dim uniquePairs = From p In allpairs Where p.a Mod 2 <> 0 Select p

note: the last pair is missing, working on it

Edit:

union uniquePairs with the pair {nums.Last,0}

@Cristi Diaconescu 2010-12-16 14:01:50

That's not what I asked for.

@Ali Tarhini 2010-12-16 14:21:56

i didnt notice that the pairs were in seuqence. i edited the answer

@Ed'ka 2010-12-16 14:28:31

    var w =
        from ei in nums.Select((e, i) => new { e, i })
        group ei.e by ei.i / 2 into g
        select new { f = g.First(), s = g.Skip(1).FirstOrDefault() };

@Yakimych 2010-12-16 14:08:36

This might be a bit more general than you require - you can set a custom itemsInGroup:

int itemsInGroup = 2;
var pairs = nums.
            Select((n, i) => new { GroupNumber = i / itemsInGroup, Number = n }).
            GroupBy(n => n.GroupNumber).
            Select(g => g.Select(n => n.Number).ToList()).
            ToList();

EDIT:

If you want to append zeros (or some other number) in case the last group is of a different size:

int itemsInGroup = 2;
int valueToAppend = 0;
int numberOfItemsToAppend = itemsInGroup - nums.Count() % itemsInGroup;

var pairs = nums.
            Concat(Enumerable.Repeat(valueToAppend, numExtraItems)).
            Select((n, i) => new { GroupNumber = i / itemsInGroup, Number = n }).
            GroupBy(n => n.GroupNumber).
            Select(g => g.Select(n => n.Number).ToList()).
            ToList();

@Cristi Diaconescu 2010-12-16 14:15:29

Cool! One caveat, the last item in pairs will have only 1 element if the list of numbers has an odd count. E.g. nums = {1,2,3} => pairs = { {1, 2}, {3} }

@Yakimych 2010-12-16 14:19:27

See update for the general case. If you only need this with two items per group, you can do a simpler check for nums.Count() and append one 0 if it's odd.

@max 2010-12-16 14:14:34

(warning: looks ugly)

var pairs = x.Where((i, val) => i % 2 == 1)
            .Zip(
            x.Where((i, val) => i % 2 == 0),
                (first, second) =>
                new
                {
                    First = first,
                    Second = second
                })
            .Concat(x.Count() % 2 == 1 ? new[]{
                new
                {
                    First = x.Last(),
                    Second = default(int)
                }} : null);

@Cristi Diaconescu 2010-12-16 14:31:43

Stealing from Danny Chen, you could append a '0' element to the 2nd argument of Zip and thus get rid of your last .Concat(...) block.

@Cheng Chen 2010-12-16 14:09:41

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7 };
var result = numbers.Zip(numbers.Skip(1).Concat(new int[] { 0 }), (x, y) => new
        {
            First = x,
            Second = y
        }).Where((item, index) => index % 2 == 0);

@Cheng Chen 2010-12-16 14:21:49

I will always add an element whose value is 0, it will be automatically ignored if the length of numbers is even.

@Cristi Diaconescu 2010-12-16 14:21:51

I wasn't aware there's a Where() version that supports indexing. +1

@Cristi Diaconescu 2010-12-16 14:27:17

And it works for lists of odd length too :)

@Mr. TA 2010-12-16 13:49:30

Try this:

int i = 0;
var pairs = 
  nums
    .Select(n=>{Index = i++, Number=n})
    .GroupBy(n=>n.Index/2)
    .Select(g=>{First:g.First().Number, Second:g.Last().Number});

@Cristi Diaconescu 2010-12-16 13:52:28

you can do .Select((n, i)=>...) to get an automatic counter

Related Questions

Sponsored Content

9 Answered Questions

[SOLVED] Can anonymous class implement interface?

  • 2008-10-10 12:20:32
  • Nick Randell
  • 150971 View
  • 433 Score
  • 9 Answer
  • Tags:   c# anonymous-types

11 Answered Questions

[SOLVED] Sorting a list using Lambda/Linq to objects

26 Answered Questions

[SOLVED] Why not inherit from List<T>?

15 Answered Questions

[SOLVED] Using LINQ to remove elements from a List<T>

  • 2009-05-12 15:56:24
  • TK.
  • 553032 View
  • 623 Score
  • 15 Answer
  • Tags:   c# .net linq list

10 Answered Questions

[SOLVED] Remove duplicates in the list using linq

10 Answered Questions

[SOLVED] IEnumerable vs List - What to Use? How do they work?

6 Answered Questions

[SOLVED] Pairs from single list

19 Answered Questions

[SOLVED] How to Sort a List<T> by a property in the object

15 Answered Questions

[SOLVED] How would you do a "not in" query with LINQ?

  • 2008-10-08 17:01:40
  • Brennan
  • 301052 View
  • 287 Score
  • 15 Answer
  • Tags:   c# linq

12 Answered Questions

[SOLVED] Find an item in List by LINQ?

  • 2009-07-24 03:42:29
  • David.Chu.ca
  • 665615 View
  • 212 Score
  • 12 Answer
  • Tags:   c# linq

Sponsored Content