Skip to content

Instantly share code, notes, and snippets.

@benaston
Created March 6, 2014 09:52
Show Gist options
  • Save benaston/9386397 to your computer and use it in GitHub Desktop.
Save benaston/9386397 to your computer and use it in GitHub Desktop.
Random C#
///<summary>
/// Returns a dictionary of lists keyed by row index.
/// Each list in the dictionary corresponds to a row of values.
/// "kvp" stands for "key-value pair".
///</summary>
public class ListHelper
{
public static Dictionary<int, List<T>> ToVertical<T>(IEnumerable<T> list, int maxColumns) {
if(list == null) {
throw new ArgumentNullException("list");
}
if(list.Count() < 1) {
throw new ArgumentException("`list` must contain one or more values.");
}
if(maxColumns < 1) {
throw new ArgumentException("`maxColumns` should be one or greater.");
}
var verticalDictionary = new Dictionary<int, List<T>>();
var rows = (int)Math.Ceiling((double)(list.Count())/maxColumns); //Calculate the no. of rows.
//Map the supplied list into a list of key-value-pairs.
var kvps = list.Select((c, index) => {
return new { Key = index%rows, Value = c };
});
//Enumerate the key-value-pairs from the previous step and place their values in the verticalDictionary.
foreach(var kvp in kvps) {
if(verticalDictionary.Any(k => k.Key == kvp.Key)) {
verticalDictionary[kvp.Key].Add(kvp.Value);
} else {
verticalDictionary.Add(kvp.Key, new List<T> { kvp.Value });
}
}
return verticalDictionary;
}
}
//Example usage...
var countries = new string [] { "Angola", "Burundi", "Chile", "Denmark", "Estonia", "France", "Germany", "Holland", "India", "Jamaica", "Kiribati", "Laos", "Moldova" };
var maxColumns = 4;
var verticalValues = ListHelper.ToVertical(countries, maxColumns);
var maxKey = verticalValues.Max(kvp => kvp.Key);
for(int i = 0; i <=maxKey; i++) {
Console.Write(String.Join(" | ", verticalValues[i]) + "\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment