Sort a list by columns but iterate by rows

February 24th, 2019

If you have a list of objects, lets say of strings ordered alphanumerically; “A”, “B”, “C”, “D” and you want to sort them by columns like the following, yet print them out by rows.
A C
B D

Here is a refined, rows-iterable, version of a previous method I blogged here: Sorting columns using a list of objects (c#).

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System.Collections.Generic;
 
/// <summary>
/// Used to sort a list of objects into columns, ready to
/// render by iterating each row of the resulting array of lists.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceList">The source list, sorted as the desired output</param>
/// <param name="columns">The desired number of columns to sort the list by</param>
/// <returns>An array with lists of T sorted by columns but grouped in rows</returns>
public List<T>[] SortByColumns<T>(List<T> sourceList, int columns) {
	if(sourceList == null || sourceList.Count == 0 || columns < 2)
		return null;
 
	var total = sourceList.Count;
	var columnLimit = (total + (columns - 1)) / columns; // better than Ceiling((double)total / columns)
 
	var targetList = new List<T>[columnLimit];
	for(var c = 0; c < targetList.Length; c++) {
		targetList[c] = new List<T>();
	}
 
	for(var i = 0; i < total;) {
		foreach(var row in targetList) {
			row.Add(i < total ? sourceList[i++] : default(T));
		}
	}
 
	return targetList;
}

Leave a Reply