Sử dụng DataView để lấy dữ liệu theo điều kiện nào đó 1 cách nhanh chóng.
Demo:
Tạo 1 DataTable chứa thông tin tên và tuổi của một số người:
- DataTable table = new DataTable("table");
- table.Columns.Add(new DataColumn("Name", typeof(string)));
- table.Columns.Add(new DataColumn("Age", typeof(int)));
- for (int i = 0; i < 5; i++)
- {
- DataRow NewRow = table.NewRow();
- NewRow["Name"] = "Nguyễn Văn " + i;
- NewRow["Age"] = i;
- table.Rows.Add(NewRow);
- }
- // new 1 DataView
- DataView dataView = new DataView(table);
- // chỉ lấy những người có tuổi lớn hơn 2
- dataView.RowFilter = "Age > 2";
Sử dụng 2 hàm sau để test kết quả:
- private static void PrintTable(DataTable table)
- {
- for (int i = 0; i < table.Rows.Count; i++)
- {
- Console.WriteLine("\t" + table.Rows[i]["Name"] +": "+ table.Rows[i]["Age"] + " tuổi.");
- }
- Console.WriteLine();
- }
- private static void PrintView(DataView view)
- {
- for (int i = 0; i < view.Count; i++)
- {
- Console.WriteLine("\t" + view[i]["Name"] + ": " + view[i]["Age"] + " tuổi.");
- }
- Console.WriteLine();
- }
- DataTable table = new DataTable("table");
- table.Columns.Add(new DataColumn("Name", typeof(string)));
- table.Columns.Add(new DataColumn("Age", typeof(int)));
- for (int i = 0; i < 5; i++)
- {
- DataRow NewRow = table.NewRow();
- NewRow["Name"] = "Nguyễn Văn " + i;
- NewRow["Age"] = i;
- table.Rows.Add(NewRow);
- }
- // new 1 DataView
- DataView dataView = new DataView(table);
- // chỉ lấy những người có tuổi lớn hơn 2
- dataView.RowFilter = "Age > 2";
- PrintTable(table);
- PrintView(dataView);
- Console.ReadLine();
Không có nhận xét nào :
Đăng nhận xét