using System; using System.Data; namespace LinqUseInAdoNetDemo { /// <summary> /// Linq 在 ADO.NET 的 使用 /// https://www.cnblogs.com/LifeDecidesHappiness/p/8079142.html /// 2021-9-15 /// </summary> internal class Program { private static void Main() { Console.Title = "Linq 在 ADO.NET 的 使用"; LinqInAdoNetDemo(); Console.ReadKey(); } private static void LinqInAdoNetDemo() { var dt = GetDataTable(); // Lambda Expression // var query = dt.AsEnumerable().OrderBy(x => x.Field<int>("Age")); // Linq Expression var query = from x in dt.AsEnumerable() orderby x.Field<int>("Age") select x; foreach (var dataRow in query) Console.WriteLine("【编号】{0} \t 【姓名】{1} \t 【年龄】{2}", dataRow.Field<int>("Id"), dataRow.Field<string>("Name"), dataRow.Field<int>("Age")); } /// <summary> /// 手动创建 DataTable /// </summary> /// <returns></returns> public static DataTable GetDataTable() { var dt = new DataTable(); // Columns dt.Columns.AddRange(new[] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Age", typeof(int)) }); // Data Rows var row = dt.NewRow(); row["Id"] = 1; row["Name"] = "LDH"; row["Age"] = 28; dt.Rows.Add(row); row = dt.NewRow(); row["Id"] = 2; row["Name"] = "Jack"; row["Age"] = 50; dt.Rows.Add(row); row = dt.NewRow(); row["Id"] = 3; row["Name"] = "Jason"; row["Age"] = 18; dt.Rows.Add(row); return dt; } } }