C# Datatable 轉換為列表(開發者的工作原理)
在 C# 中將 DataTable 轉換為清單
在 C# 程式設計領域,經常會遇到需要將 DataTable 轉換為清單的情況。許多新手都會遇到這個問題,但他們往往找不到足夠全面的答案。 本教程旨在彌合這一差距,並提供一個清晰的指南,說明如何在 C# 中將 DataTable 轉換為清單。
什麼是 DataTable?
在深入了解轉換過程之前,了解DataTable是什麼至關重要。 在 C# 中,DataTable 物件是記憶體資料庫表的表示,該表具有行和列。 它是 System.Data 命名空間的一部分。
為了本教學的目的,我們使用一個名為 dt 的範例 DataTable。 如下圖所示,可將其視覺化:
using System.Data;
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Category", typeof(string));
dt.Rows.Add(1, "Electronics");
dt.Rows.Add(2, "Books");
using System.Data;
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Category", typeof(string));
dt.Rows.Add(1, "Electronics");
dt.Rows.Add(2, "Books");
Imports System.Data
Private dt As New DataTable()
dt.Columns.Add("ID", GetType(Integer))
dt.Columns.Add("Category", GetType(String))
dt.Rows.Add(1, "Electronics")
dt.Rows.Add(2, "Books")
開始轉換
所以,你現在有了 DataTable dt,然後你盯著它想,"我該如何轉換它?" 不用擔心; 這是一個顯示研究努力的問題。 將 DataTable 轉換為清單主要有兩種方法:
1.使用 LINQ(語言整合查詢)
- 使用經典的
foreach循環
使用 LINQ 進行轉換
LINQ 方法是 C# 中的一種強大工具,它提供了一種以聲明方式查詢集合的方法。 讓我們來看看如何做到這一點。
定義方法如下:
using System.Linq;
using System.Collections.Generic;
private static List<dynamic> LinqMethod(DataTable dt)
{
return dt.AsEnumerable().Select(row =>
new
{
ID = row.Field<int>("ID"),
Category = row.Field<string>("Category")
}).ToList();
}
using System.Linq;
using System.Collections.Generic;
private static List<dynamic> LinqMethod(DataTable dt)
{
return dt.AsEnumerable().Select(row =>
new
{
ID = row.Field<int>("ID"),
Category = row.Field<string>("Category")
}).ToList();
}
'INSTANT VB NOTE: 'Option Strict Off' is used here since dynamic typing is used:
Option Strict Off
Imports System.Linq
Imports System.Collections.Generic
'INSTANT VB NOTE: In the following line, Instant VB substituted 'Object' for 'dynamic' - this will work in VB with Option Strict Off:
Private Shared Function LinqMethod(ByVal dt As DataTable) As List(Of Object)
Return dt.AsEnumerable().Select(Function(row) New With {
Key .ID = row.Field(Of Integer)("ID"),
Key .Category = row.Field(Of String)("Category")
}).ToList()
End Function
在上面的程式碼中,對 AsEnumerable() 呼叫了擴充方法 DataTable dt。 這樣我們就可以在 DataRow 中的每個 DataTable 上使用 LINQ。 此方法建立了一個動態物件列表,每個物件代表來自 DataTable 的一行。
使用 foreach 循環進行轉換
foreach 迴圈是 C# 中遍歷集合的一種經過驗證的方法。 這個方法看起來可能有點長,但卻很容易理解和實施。
工作方式如下
private static List<Category> ForeachMethod(DataTable dt)
{
List<Category> list = new List<Category>();
// Iterates through each row within the data table
foreach (DataRow row in dt.Rows)
{
var category = new Category
{
ID = Convert.ToInt32(row["ID"]),
Name = row["Category"].ToString()
};
list.Add(category);
}
return list;
}
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
private static List<Category> ForeachMethod(DataTable dt)
{
List<Category> list = new List<Category>();
// Iterates through each row within the data table
foreach (DataRow row in dt.Rows)
{
var category = new Category
{
ID = Convert.ToInt32(row["ID"]),
Name = row["Category"].ToString()
};
list.Add(category);
}
return list;
}
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
Private Shared Function ForeachMethod(ByVal dt As DataTable) As List(Of Category)
Dim list As New List(Of Category)()
' Iterates through each row within the data table
For Each row As DataRow In dt.Rows
Dim category As New Category With {
.ID = Convert.ToInt32(row("ID")),
.Name = row("Category").ToString()
}
list.Add(category)
Next row
Return list
End Function
Public Class Category
Public Property ID() As Integer
Public Property Name() As String
End Class
在 ForeachMethod 方法中,使用 foreach 循環遍歷 DataTable。對於每個 DataRow,實例化一個新的 Category 物件並將其新增至 list。
進階轉換技術的延伸
在掌握了將 DataTable 轉換為 C# 清單的基礎知識之後,還有一些高級技巧和注意事項可以優化此過程並將其適應更複雜的場景。 讓我們深入探討其中一些技巧。
使用反射將 DataTable 轉換為列表
Reflection 是 C# 中的強大工具,可讓您在執行時檢查類型的元資料。讓我們利用它的力量:
using System.Reflection;
private static List<t> ConvertDataTableToList<t>(DataTable dt) where T : new()
{
List<t> list = new List<t>();
foreach (DataRow row in dt.Rows)
{
T obj = new T();
foreach (DataColumn col in dt.Columns)
{
var prop = obj.GetType().GetProperty(col.ColumnName);
if (prop != null && row[col] != DBNull.Value)
prop.SetValue(obj, row[col]);
}
list.Add(obj);
}
return list;
}
using System.Reflection;
private static List<t> ConvertDataTableToList<t>(DataTable dt) where T : new()
{
List<t> list = new List<t>();
foreach (DataRow row in dt.Rows)
{
T obj = new T();
foreach (DataColumn col in dt.Columns)
{
var prop = obj.GetType().GetProperty(col.ColumnName);
if (prop != null && row[col] != DBNull.Value)
prop.SetValue(obj, row[col]);
}
list.Add(obj);
}
return list;
}
Imports System.Reflection
Private Shared Function ConvertDataTableToList(Of T As New)(dt As DataTable) As List(Of T)
Dim list As New List(Of T)()
For Each row As DataRow In dt.Rows
Dim obj As New T()
For Each col As DataColumn In dt.Columns
Dim prop = obj.GetType().GetProperty(col.ColumnName)
If prop IsNot Nothing AndAlso row(col) IsNot DBNull.Value Then
prop.SetValue(obj, row(col))
End If
Next
list.Add(obj)
Next
Return list
End Function
此 ConvertDataTableToList 方法採用反射,遍歷 DataRow 中的每個 DataTable 列。 對於每一列,它會在一般物件中搜尋匹配的屬性,並設定其值。 這種方法允許使用高度可重複使用的方法,可以將任何 DataTable 轉換為通用物件清單。
用途
若要使用上述程式碼,只需透過指定類型來呼叫方法即可:
List<Category> categories = ConvertDataTableToList<Category>(dt);
List<Category> categories = ConvertDataTableToList<Category>(dt);
Dim categories As List(Of Category) = ConvertDataTableToList(Of Category)(dt)
有了這種方法,您就不再局限於將特定的資料表轉換為特定的物件類型。取而代之的是,您擁有了一個可以處理各種資料情境的多功能工具。
效能考量
雖然反射法很強大,但值得注意的是,它的速度可能較慢,尤其是對於大型資料表。 衡量性能並與代碼的可重用性和可維護性的優點進行權衡始終是至關重要的。
適用於 .NET 開發人員的 Iron Suite 工具包。
雖然我們已經深入研究了在 C# 中將 DataTable 轉換為清單的複雜性,但有時,依賴外部工具可以簡化我們的開發過程,尤其是在處理更複雜的操作時。 這就是 Iron Suite 發揮作用的地方。
IronPDF:PDF 的強大功能

說到用 C# 處理 PDF,IronPDF 可說是改變了遊戲規則。 想像一下,你已經將 DataTable 轉換成了一個列表,然後需要從中產生一個 PDF 報告。 IronPDF 可以毫不費力地從 PDF 文件中建立、編輯和擷取資料,簡化將您的資料表衍生資訊翻譯成外觀專業的報表的流程。
IronPDF 的主要功能是其 HTML to PDF 功能,可確保版面設計和樣式得以保留。 它能從網頁內容產生 PDF,適用於報告、發票和文件。 您可以毫不費力地將 HTML 檔案、URL 和 HTML 字串轉換為 PDF 檔案。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
IronXL:卓越的 Excel 作業
。
如果您的 DataTable 轉換導致需要使用 Excel 相關任務, IronXL就是您應該使用的工具。 本產品提供閱讀、編輯和建立 Excel 試算表的無縫操作。 有了資料表轉換為清單,使用 IronXL.Excel 將資料匯出為 Excel 格式就變得非常簡單。
IronOCR:讓文字可被辨識。
。
有時,您的 DataTable 可能包含基於圖像的數據,或者您需要從圖像中提取文字。 這就是 IronOCR 發光發熱的地方。 它允許 .NET 開發人員從圖像中讀取文本,如果您的 DataTable 轉換操作涉及包含文字資訊的圖像,則它是一個補充工具。
IronBarcode:字裡行間的解讀

最後,IronBarcode是您應用程式中任何條碼操作的必備工具。 假設您的 DataTable 或您將其轉換後的清單包含帶有條碼的產品資訊。 在這種情況下,IronBarcode 提供了讀取和生成條碼的有效機制,在原始產品資料和可掃描的條碼資訊之間架起了一座橋樑。
結論

雖然手動操作和轉換 DataTable 的方法對於任何 C# 開發人員來說都至關重要,但整合 Iron Suite 等提供的強大工具可以成倍提高您的生產力和能力。 值得注意的是,每個產品授權都從 $999 開始,更吸引人的是,每個產品都提供免費試用。 如果您正在考慮投資這些工具,現在有一個誘人的優惠:您可以只花兩個產品的價錢就能獲得整個 Iron Suite。 採用這種全面的解決方案,無疑可以提升您的 .NET 開發工作的品質與效率。
常見問題解答
什麼是 C# 中的 DataTable?
C# 中的 DataTable 是一個在記憶體中的資料庫表格表示,由行和列組成。它是 System.Data 命名空間的一部分。
如何使用 LINQ 將 DataTable 轉換為 C# 中的清單?
您可以使用 LINQ 將 DataTable 轉換為清單,透過利用 AsEnumerable() 方法遍歷每個 DataRow 並使用 Select 創建代表每行的動態物件清單。
使用 foreach 迴圈在 C# 中將 DataTable 轉換為清單的過程是什麼?
要使用 foreach 迴圈將 DataTable 轉換為清單,請遍歷每個 DataRow,為每行建立一個新物件,從 DataRow 中填入其屬性,然後將其添加到清單中。
反射如何增強 C# 中的 DataTable 轉換?
使用反射允許高度可重用的方法,透過動態地將 DataTable 欄位映射到物件屬性,將任何 DataTable 轉換為泛型物件清單。
IronPDF 如何幫助處理從 DataTables 派生的 PDF?
IronPDF 允許開發人員創建、編輯和提取 PDF 文件中的資料,這對於生成從 DataTable 派生的資料報告非常有用。
IronXL 在 C# 中的 Excel 操作優勢?
IronXL 促進了從 DataTables 到 Excel 格式的資料匯出,允許開發人員輕鬆地讀取、編輯和創建 Excel 試算表。
IronOCR 可以以哪些方式應用於 DataTables?
IronOCR 可以從 DataTables 中的圖像讀取文字,讓開發人員能夠處理含有文字資訊的圖像資料。
IronBarcode 如何增強與條碼相關的 DataTable 操作?
IronBarcode 提供讀取和生成條碼的能力,這對於包含條碼的產品資訊的 DataTables 或清單很有助益。
在使用反射進行 DataTable 轉換時需要考慮哪些性能因素?
雖然反射提供了彈性,但尤其對於大型資料表來說,可能會比其他方法慢,因此需要平衡性能與重用性和可維護性。
Iron Software 產品是否有可用的授權和試用機會?
是的,文章提到 Iron Suite 產品有可用的授權和試用機會,允許開發人員在購買前評估這些工具。



