Get groups of 4 elements from name value list using LINQ in C#

前端 未结 3 724
执笔经年
执笔经年 2021-01-19 03:29

I am wanting to loop through this list of name value pairs and grab them in groups of 4.

The data would be like:

value1 1
value2 1
value3 1
value4 1
         


        
相关标签:
3条回答
  • 2021-01-19 03:52

    I think you're looking for GroupBy.

    0 讨论(0)
  • 2021-01-19 03:53

    There's nothing built into the framework to do this easily, but MoreLINQ has the Batch method:

    IEnumerable<IEnumerable<DataItem>> groups = source.Batch(4);
    
    foreach (IEnumerable<DataItem> group in groups)
    {
        foreach (DataItem item in group)
        {
            ...
        }
    }
    
    0 讨论(0)
  • 2021-01-19 04:13

    This will group by every 4 items (a, b, c, d), (e, f, g, h), (i, j)

    var abc = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
    
    var xyz = abc.Select((e, i) => new { Item = e, Grouping = (i / 4) }).GroupBy(e => e.Grouping);
    
    0 讨论(0)
提交回复
热议问题