Linq Pager 페이징
출처 : http://channel9.msdn.com/forums/TechOff/253890-Cool-Linq-Sample-0-Linq-Pager/
Each week till Linq launches I am going to post a Linq sample that shows off some Linq features.
This week how you make a pager function using linq.
Paging is used to work with abstract idea of collection of containers that can hold something of a given type to lead users through a long list of items. A pager is something that can return a given container given some page size and which page the developer wants to return.
Linq can model this idea of pager in 1 line of code. Two IEnumerable<T> extension methods from System.Query namespace are used Skip and Take.
Skip(int) is called first this tells Enumerator to ignore a certain number of items represented as an int. The function assume the first page has a page number of 1 though you could certainly not decrement if you like to remain zero based.
Take(int) constrains the number of items returned which we represent with the pageSize.
public static IEnumerable<T> GetPage<T>
(int pageNumber, int pageSize, IEnumerable<T> list)
{
var output = list
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return output;
}
Here is a Windows Form Sample that uses the pager to iterate through a listing of DLLs in "C:\WINDOWS\Microsoft.NET\". This can be changed to prompt user for a value or a directory more appropriate to your testing OS folder structure.
The Window Form used consists of 4 controls:
Button id = Back
Button id = Next
Textbox id = Page
ListView id = FileView (change View to 'List')
Here is the code behind for the form:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace _PagingThroughFiles
{
public partial class Form1 : Form
{
private IEnumerable<FileInfo> m_Files;
private IEnumerable<FileInfo> m_Results;
private int m_PageSize = 25;
public Form1()
{
InitializeComponent();
DirectoryInfo DI = new DirectoryInfo(@"C:\WINDOWS\Microsoft.NET\");
m_Files =
from file in DI.GetFiles("*", SearchOption.AllDirectories)
where file.Extension == ".dll"
orderby file.FullName
select file;
BindUI(1, m_PageSize);
}
private void BindUI(int pageNumber, int pageSize)
{
FileView.Items.Clear();
m_Results = GetPage<FileInfo>(pageNumber, pageSize, m_Files);
foreach (var file in m_Results)
{
FileView.Items.Add(new ListViewItem(file.FullName));
}
Page.Text = pageNumber.ToString();
Back.Enabled = pageNumber != 1;
Next.Enabled = ((pageNumber * pageSize) + 1) <= m_Files.Count();
}
private void Back_Click(object sender, EventArgs e)
{
BindUI(int.Parse(Page.Text) - 1, m_PageSize);
}
private void Next_Click(object sender, EventArgs e)
{
BindUI(int.Parse(Page.Text) + 1, m_PageSize);
}
public static IEnumerable<T> GetPage<T>
(int pageNumber, int pageSize, IEnumerable<T> list)
{
var output = list
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
return output;
}
}
}