C# 数据表转列表(开发者如何使用)
Converting DataTable to List in C#
在 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 转换为列表主要有两种方法:
- 使用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 方法中,使用 DataTable 循环遍历 foreach。对于每个 DataRow,实例化一个新的 Category 对象并将其添加到 list。
扩展高级转换技术
在掌握了将 DataTable 转换为 C# 列表的基础知识之后,还有一些高级技巧和注意事项可以优化此过程并将其适应更复杂的场景。 让我们深入研究这些技术。
使用反射将 DataTable 转换为列表
反射是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到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电子表格。 有了数据表到列表的转换,导出数据到Excel格式变得非常简单,只需使用IronXL即可。
IronOCR:使文本可辨认

有时,您的 DataTable 可能包含基于图像的数据,或者您需要从图像中提取文本。 这就是IronOCR闪耀的地方。 它允许 .NET 开发人员从图像中读取文本,如果您的 DataTable 转换操作涉及包含文本信息的图像,则它是一个补充工具。
IronBarcode:从条形码中读取信息

最后,IronBarcode是您在应用程序中进行任何条形码操作的理想工具。 假设您的 DataTable 或您将其转换后的列表包含带有条形码的产品信息。 在这种情况下,IronBarcode提供了一个有效的机制来读取和生成条形码,弥合了原产品数据与可扫描条形码信息之间的差距。
结论

虽然手动操作和转换 DataTable 的方法对于任何 C# 开发人员来说都至关重要,但集成 Iron Suite 等提供的强大工具可以成倍提高您的生产力和能力。 值得注意的是,每个产品许可证都从 $999 开始,更吸引人的是,每个产品都提供免费试用。 如果您考虑投资这些工具,有一个诱人的报价:您可以以两个产品的价格获得整个Iron Suite。 采用这样全面的解决方案,确实可以提升您的.NET开发工作质量和效率。
常见问题解答
C#中的DataTable是什么?
C#中的DataTable是数据库表的内存表示,由行和列组成。它是System.Data命名空间的一部分。
如何在C#中使用LINQ将DataTable转换为列表?
您可以通过使用AsEnumerable()方法迭代每个DataRow并使用Select方法创建表示每一行的动态对象列表来使用LINQ将DataTable转换为列表。
在C#中使用foreach循环转换DataTable为列表的过程是怎样的?
要使用foreach循环将DataTable转换为列表,需迭代每个DataRow,为每行实例化一个新对象,从DataRow中填充其属性,并将其添加到列表中。
反射如何增强C#中的DataTable转换?
通过使用反射,可以通过动态映射DataTable列到对象属性,实现一个高度可重用的方法,将任意DataTable转换为通用对象的列表。
IronPDF如何在处理从DataTable派生的PDF中提供帮助?
IronPDF使开发人员能够创建、编辑和从PDF文档中提取数据,这对于从DataTable派生的数据生成报告非常有用。
IronXL在C#中的Excel操作有什么优势?
IronXL促进了从DataTable到Excel格式的数据导出,使开发人员能够轻松高效地读取、编辑和创建Excel电子表格。
IronOCR可以在哪些方面应用于DataTable?
IronOCR可以从DataTable内的图像中读取文本,使开发人员能够处理包含文本信息的基于图像的数据。
IronBarcode如何通过条形码增强DataTable操作?
IronBarcode提供了读取和生成条形码的功能,对于包含条形码产品信息的DataTable或列表非常有益。
在使用反射进行DataTable转换时,应注意哪些性能考虑?
尽管反射提供了灵活性,但通常比其他方法慢,尤其是在处理大型数据表时,因此在性能、可重用性和可维护性之间找到平衡很重要。
Iron Software产品是否有许可和试用机会?
是的,文章提到Iron Suite产品提供许可和试用机会,让开发人员在购买前评估工具。




