Linq to Objects - return pairs of numbers from list of numbers
Asked Answered
S

12

12
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}.

Severe answered 16/12, 2010 at 13:45 Comment(6)
Exact duplicate of question asked by yourself #3576425Urology
@Jani No, it's not. That's asking for an equivalent to Python's (or Ruby's) Zip() method -> takes two lists and makes one list of tuples. This question is about partitioning a single list.Severe
A very similar answer -- for sliding window to get {{1,2},{2,3},{3,4}... -- which should be easy to adapt is here: #578090Hypochlorite
@Jani Actually I was wrong too, that question is not about the Zip() method, but still, it's a different question.Severe
@Hypochlorite That uses a custom iterator, not a Linq expression. I do admit that this might be the cleanest way to go though.Severe
@Cristi, Finally I come up with the solution :-)Urology
L
10

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;
}
Leathern answered 16/12, 2010 at 14:47 Comment(3)
Looking at all the answers, it does seem that Linq is not the best approach here. Your implementation is pretty clean.Severe
It should be public static IEnumerable<T[]> Partition<T>....Briones
I added bool includePartial = true to the parameters and check that as well during the leftovers step. In my case I am using this for input into BitConverter.ToInt32, which requires sets of 4.Impoverished
U
3

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});
Unmuzzle answered 16/12, 2010 at 13:49 Comment(1)
you can do .Select((n, i)=>...) to get an automatic counterSevere
R
1

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();
Rankle answered 16/12, 2010 at 14:8 Comment(2)
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} }Severe
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.Rankle
W
1
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);
Warrior answered 16/12, 2010 at 14:9 Comment(2)
I will always add an element whose value is 0, it will be automatically ignored if the length of numbers is even.Warrior
I wasn't aware there's a Where() version that supports indexing. +1Severe
D
1

(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);
Doughman answered 16/12, 2010 at 14:14 Comment(1)
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.Severe
R
1
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();
Revitalize answered 17/12, 2010 at 14:48 Comment(0)
M
1
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);
Monastery answered 28/7, 2016 at 16:33 Comment(0)
U
0
 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] });
Urology answered 16/12, 2010 at 13:51 Comment(2)
That will return pairs as {{1,2}, {2,3}, ...}Rankle
@Lasse It works fine as I understand the question so please revoke your downvoteUrology
P
0
    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() };
Pengelly answered 16/12, 2010 at 14:28 Comment(0)
C
0

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});
Cioban answered 3/12, 2018 at 11:9 Comment(1)
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.Severe
B
0

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().

Betancourt answered 17/6, 2019 at 16:36 Comment(0)
S
-1

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}

Seraphic answered 16/12, 2010 at 13:58 Comment(1)
i didnt notice that the pairs were in seuqence. i edited the answerSeraphic

© 2022 - 2024 — McMap. All rights reserved.