1

how can I split a sequence of numbers into subgroups of numbers and get the local minimum and maximum of the subgroups with linq?

If I have a sequence of, lets say 11 items { 3, 2, 5, 9, 9, 6, 7, 2, 5, 11, 2 }
I want to split this into subgroups with 3 or less items.

So I get the following 4 subgroups: { 3, 2, 5 } , { 9, 9, 6 } , { 7, 2, 5} , { 11, 2}

The final return values of the LinQ expression (getting min and max for each group) should be 2, 5, 6, 9, 2, 7, 2, 11

TIA, Sascha

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Sascha
  • 11
  • 1
  • You have `6` in two groups, and dropped the `5`. What if you have a group of one number? `{1,2,3}{4}`? – Kobi Oct 27 '10 at 05:24
  • @Kobi: It was likely a typo, though it didn't affect what the desired result would be (as far as I can tell). – Jeff Mercado Oct 27 '10 at 05:30
  • possible duplicate of [Split List into Sublists with LINQ](http://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq) – nawfal Feb 18 '13 at 10:32

2 Answers2

4

This should do it.

var numbers = new[] { 3, 2, 5, 9, 9, 6, 7, 2, 5, 11, 2 };
var query = from p in numbers.Select((n, i) => new { n, Group = i / 3 })
            group p.n by p.Group into g
            from n in new[] { g.Min(), g.Max() }
            select n;
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
3

Well, using MoreLINQ's Batch method to do the grouping, you could use:

var query = source.Batch(3, batch => new[] { batch.Min(), batch.Max() })
                  .SelectMany(x => x);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • One point is that the last item will be doubled if it is alone in its group. `{1}`->`{1,1}`. Of course, it fits the requirements. – Kobi Oct 27 '10 at 05:33