[C# Lambda] DataTable.AsEnumerable()使用範例
範例
0. 篩選
class Program { static void Main() { DataTable table = GetSampleDataTable(); var filteredRows = table.AsEnumerable() .Where(row => row.Field<int>("Age") > 25) .ToList(); foreach (var row in filteredRows) { Console.WriteLine($"Name: {row["Name"]}, Age: {row["Age"]}"); } } static DataTable GetSampleDataTable() { DataTable table = new DataTable(); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Age", typeof(int)); table.Rows.Add("Alice", 28); table.Rows.Add("Bob", 22); table.Rows.Add("Charlie", 30); table.Rows.Add("David", 25); return table; } }
1. 排序(Sorting)
var sortedRows = table.AsEnumerable() .OrderBy(row => row.Field<int>("Age")) .ToList(); foreach (var row in sortedRows) { Console.WriteLine($"Name: {row["Name"]}, Age: {row["Age"]}"); }
2. 投影(Projection)
var projectedData = table.AsEnumerable() .Select(row => new { Name = row.Field<string>("Name"), Age = row.Field<int>("Age") }) .ToList(); foreach (var item in projectedData) { Console.WriteLine($"Name: {item.Name}, Age: {item.Age}"); }
3. 分組(Grouping)
var groupedData = table.AsEnumerable() .GroupBy(row => row.Field<int>("Age") / 10 * 10) .Select(group => new { AgeGroup = $"{group.Key}-{group.Key + 9}", Count = group.Count() }) .ToList(); foreach (var group in groupedData) { Console.WriteLine($"Age Group: {group.AgeGroup}, Count: {group.Count}"); }
4. 比較式
4-1 等於(Equal)
var equalRows = table.AsEnumerable() .Where(row => row.Field<string>("Name") == "Alice") .ToList();
4-2 大於等於
var greaterThanOrEqualRows = table.AsEnumerable() .Where(row => row.Field<int>("Age") >= 25) .ToList();
4-3 多條件
var multipleConditions = table.AsEnumerable() .Where(row => row.Field<string>("Name") == "Alice" && row.Field<int>("Age") > 25) .ToList();
4-4 日期
DateTime targetDate = new DateTime(1990, 1, 1); var dateComparison = table.AsEnumerable() .Where(row => row.Field<DateTime>("Birthdate") >= targetDate) .ToList();
---
留言
張貼留言