How to “zip” or “rotate” a variable number of lists?

后端 未结 8 1632
广开言路
广开言路 2020-11-27 20:47

If I have a list containing an arbitrary number of lists, like so:

var myList = new List>()
{
    new List() { \"a\",          


        
8条回答
  •  春和景丽
    2020-11-27 21:00

    How about using SelectMany and GroupBy with some indexes?

    // 1. Project inner lists to a single list (SelectMany)
    // 2. Use "GroupBy" to aggregate the item's based on order in the lists
    // 3. Strip away any ordering key in the final answer
    var query = myList.SelectMany(
        xl => xl.Select((vv,ii) => new { Idx = ii, Value = vv }))
           .GroupBy(xx => xx.Idx)
           .OrderBy(gg => gg.Key)
           .Select(gg => gg.Select(xx => xx.Value));
    

    From LinqPad:

    we groupa da items

提交回复
热议问题