开发者

List to Columns in LINQ

开发者 https://www.devze.com 2023-01-01 16:44 出处:网络
Given an IEnumerable<T> and row count, I would like to convert it to an IEnumerable<IEnumerable<T>> like so:

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?


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


var src = new List<int> { 2, 4, 8, 16, 23, 42, 101 };
var i = 0;
var answer = src.GroupBy(item => i++ % 3)
                .Select(item => item.ToArray())
                .ToArray();

hehe, and with this trick we can avoid temporary variable, but code become unreadable:

        var src = new int[] { 4, 8, 15, 16, 23, 42, 101 };

        var b = Enumerable.Range(0, src.Length)
                   .Select(index => index)
                   .GroupBy(index => index % 3)
                   .Select(indexes => indexes.Select(index => src[index]).ToArray())
                   .ToArray();


This will grab groups of 3 if that's what your after?

Nasty approach though :-)

int[] list = new [] {1,2,3,4,5,6,7};

    int count = 0;

    var x =
        from i in list.Where((c,i)=> i%3==0)
        let grp = list.Skip(count).Take(3)
        let temp = (count+=3)
        select new {
            grp
        };


Something like this should work.

int[] list = new[] {1,2,3,4,5,6,7};
int[] offsets = new[] {0,1,2};
int[][] sorted = 
    offsets.Select((offset) => list.TakeWhile((_,ix,_) => ix % 3 == offset))

Warning: not tested. I don't program in c#, but the idea should be clear.

0

上一篇:

:下一篇

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号