Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List to Columns in LINQ

Tags:

c#

linq

Given an IEnumerable<T> and row count, I would like to convert it to an IEnumerable<IEnumerable<T>> like so:

Input:

Row Count: 3

List: [1,2,3,4,5,6,7]

Output

 
[
 [1,4,7]
 [2,5]
 [3,6]
]

EDIT I would like this to work for any IEnumerable and not depend on T being an Int32.

How can I do this using LINQ?

like image 574
Sam Saffron Avatar asked Jun 02 '10 07:06

Sam Saffron


1 Answers

This will do it:

var list = new List<object> { 1, "two", 3, 4, 5, 6 ,7 };
int count = 3;
var rows = list.Select((item, index) => new { Item = item, Index = index })
            .GroupBy(o => o.Index % count)
            .Select(g => g.Select(o => o.Item));

It should work for any Enumerable

like image 179
David M Avatar answered Sep 28 '22 04:09

David M