C# Datatable 轉換為列表(開發者的工作原理)
在 C# 中將 DataTable 轉換為 List;。
通常,在使用 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(語言整合查詢) 2.使用經典的 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 上呼叫。 這可讓我們在 DataTable 中的每個 DataRow 上使用 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 中。
進階轉換技術的延伸
在掌握了在 C# 中將 DataTable 轉換為清單的基本技巧之後,還有一些進階技術和注意事項可以優化這個流程,並使其適用於更複雜的情境。 讓我們深入探討其中一些技巧。
使用反射將 DataTable 轉換為 List.
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)(ByVal 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 col
list.Add(obj)
Next row
Return list
End Function此 ConvertDataTableToList 方法採用反射,迭代 DataTable 中的每個 DataRow 和列。 對於每一列,它會在一般物件中搜尋匹配的屬性,並設定其值。 此方法允許高度可重複使用的方法,可將任何 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 ClassIronXL:卓越的 Excel 作業
。
如果您的 DataTable 轉換導致需要執行 Excel 相關工作,IronXL 就是您應該求助的工具。 本產品提供閱讀、編輯和建立 Excel 試算表的無縫操作。 有了資料表轉換為清單,使用 IronXL.Excel 將資料匯出為 Excel 格式就變得非常簡單。
IronOCR:讓文字可被辨識。
。
有時候,您的 DataTable 可能會包含以影像為基礎的資料,或者您需要從影像中抽取文字。 這就是 IronOCR 發光發熱的地方。 它允許 .NET 開發人員從影像中讀取文字,如果您的 DataTable 轉換作業涉及包含文字資訊的影像,那麼它就是一個輔助工具。
IronBarcode:字裡行間的解讀

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

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







