LINQ swap columns into rows

前端 未结 5 1903
死守一世寂寞
死守一世寂寞 2020-12-06 10:44

Is there a fancy LINQ expression that could allow me to do the following in a much more simpler fashion. I have a List>, assuming the L

5条回答
  •  [愿得一人]
    2020-12-06 11:40

    I am combining some of the answers above, which sometimes had columns and rows inverted form the original answer or from the convention I am used to : row refers to the first index and column to the inner ( second) index. e.g. values[row][column]

        public static List> Transpose(this List> values)
        {
            if (values.Count == 0 || values[0].Count == 0)
            {
                return new List>();
            }
    
            int ColumnCount = values[0].Count;
    
            var listByColumns = new List>();
            foreach (int columnIndex in Enumerable.Range(0, ColumnCount))
            {
                List valuesByColumn = values.Select(value => value[columnIndex]).ToList();
                listByColumns.Add(valuesByColumn);
            }
            return listByColumns;
        }            
    

    Actually the word row and column is just our convention of thinking about the data in rows and columns , and sometimes adds more confusion than solving them.

    We are actually just swapping the inner index for the outer index. (or flipping the indexes around). So one could also just define the following extension method. . Again I borrowed from above solutions, just put it into something I find readable and fairly compact.

    Checks that the inner lists are of equal sized are required.

        public static List> InsideOutFlip(this List> values)
        {
            if (values.Count == 0 || values[0].Count == 0)
            {
                return new List>();
            }
    
            int innerCount = values[0].Count;
    
            var flippedList = new List>();
            foreach (int innerIndex in Enumerable.Range(0, innerCount))
            {
                List valuesByOneInner = values.Select(value => value[innerIndex]).ToList();
                flippedList.Add(valuesByOneInner);
            }
            return flippedList;
        }            
    

提交回复
热议问题