[C#.NET][LINQ] Query DataTable
本文連結:
要使用 LINQ,必須透過 AsEnumerable() + DataRow.Field(),如下範例程式碼
{ { var query = GetConsumerTable(); query.Dump("原始資料"); } { var query = from row in GetConsumerTable().AsEnumerable() where row.Field<string>("Name").Length > 4 select row ; query.Dump(); } } // Define other methods and classes here public DataTable GetConsumerTable() { DataTable table = new DataTable(); table.Columns.Add("Id"); table.Columns.Add("Name"); table.Rows.Add("1", "kobe"); table.Rows.Add("2", "jordan"); table.Rows.Add("3", "yao"); return table; }
執行結果如下圖
依上述例子手動將弱型別的 DataTable 轉成強型別 DataTable
實作 DataRow:
{ public int? Id { get { return (int)base["Id"]; } set { this["Id"] = value; } } public string Name { get { return (string)base["Name"]; } set { this["Name"] = value; } } internal ConsumerRow(DataRowBuilder builder) : base(builder) { this.Id = -1; this.Name = String.Empty; } }
再來實作 TypedTableBase<ConsumerRow>,MSDN上說:『這個型別是做為 Visual Studio 和 XSD.exe .NET Framework 工具所產生之 DataTable 型別物件的基底類別,不建議直接在您的程式碼中使用。』
不過,有了 TypedTableBase<T>,就能具有強型別的查詢
{ public ConsumerRow this[int index] { get { return (ConsumerRow)Rows[index]; } } public ConsumerTable() { this.Columns.Add(new DataColumn("Id", typeof(int))); this.Columns.Add(new DataColumn("Name", typeof(string))); } public void AddConsumerRow(ConsumerRow row) { this.Rows.Add(row); } public void RemoveConsumerRow(ConsumerRow row) { this.Rows.Remove(row); } public ConsumerRow NewConsumerRow() { return (ConsumerRow)NewRow(); } protected override Type GetRowType() { return typeof(ConsumerRow); } protected override DataRow NewRowFromBuilder(DataRowBuilder builder) { return new ConsumerRow(builder); } }
建立假資料
{ public static ConsumerTable GetConsumerTable() { ConsumerTable table = new ConsumerTable(); { ConsumerRow row = table.NewConsumerRow(); row.Id = 1; row.Name = "kobe"; table.AddConsumerRow(row); } { ConsumerRow row = table.NewConsumerRow(); row.Id = 2; row.Name = "jordan"; table.AddConsumerRow(row); } { ConsumerRow row = table.NewConsumerRow(); row.Id = 3; row.Name = "yao"; table.AddConsumerRow(row); } return table; } }
使用 LINQ Query
{ { var query = Generation.GetConsumerTable().Where(g => g.Id==1); query.Dump(); } }
執行結果如下:
PS.手動建立強型別的 DataTable 還蠻麻煩的,如果很懶,可以使用 VS 內建的 DataSet 來幫忙,不過彈性就會受限
文章出自:http://www.dotblogs.com.tw/yc421206/archive/2014/07/14/145944.aspx
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET