I was searching for a way to display a List<T>
with n elements in a user friendly and easy to handle way within the console application. So I wrote this console-list-pagiation method.
Probably there are ways to improve the usability of my approach.
public static void ConsolePaging<T>(this IEnumerable<T> Values)
{
int Pagesize = Console.WindowHeight - 2;
int PageWidth = Console.WindowWidth - 1;
int CurrentPage = 1;
int PageCount = (Values.Count() + Pagesize - 1) / Pagesize;
ConsoleKeyInfo keyInfo = new ConsoleKeyInfo();
do
{
if (keyInfo.Key == ConsoleKey.RightArrow || keyInfo.Key == (ConsoleKey)0 || keyInfo.Key == ConsoleKey.LeftArrow)
{
if (keyInfo.Key == ConsoleKey.RightArrow && CurrentPage < PageCount)
{
CurrentPage++;
}
else if (keyInfo.Key == ConsoleKey.LeftArrow && CurrentPage > 1)
{
CurrentPage--;
}
Console.Clear();
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.DarkRed;
string HeaderText = string.Format("Page:[{0}]/[{1}] │ Records:[{2}] ║ [◄] Previous │ [►] Next │ [Esc] Escape", CurrentPage, PageCount, Values.Count());
Console.WriteLine(HeaderText.PadRight(Console.BufferWidth - 1, ' '));
Console.ResetColor();
foreach (T item in Values.Skip(Pagesize * (CurrentPage - 1)).Take(Pagesize))
{
string row = item.ToString();
if (row.Length > PageWidth)
{
row = row.Substring(0, PageWidth);
}
Console.WriteLine(row);
}
}
keyInfo = Console.ReadKey(true);
} while (keyInfo.Key != ConsoleKey.Escape);
}
usage:
Enumerable.Range(1, 1000).ToList().ConsolePaging();