DataTable to Listlt;objectgt;(DataTable to Listlt;objectgt;)
问题描述
如何获取 DataTable 并将其转换为 List?
How do I take a DataTable and convert it to a List?
我在下面的 C# 和 VB.NET 中都包含了一些代码,这两者的问题是我们创建了一个新对象来返回数据,这非常昂贵.我需要返回对该对象的引用.
I've included some code below in both C# and VB.NET, the issue with both of these is that we create a new object to return the data, which is very costly. I need to return a reference to the object.
DataSetNoteProcsTableAdapters.up_GetNoteRow 对象确实实现了 INote 接口.
The DataSetNoteProcsTableAdapters.up_GetNoteRow object does implement the INote interface.
我正在使用 ADO.NET 以及 .NET 3.5
I am using ADO.NET, along with .NET 3.5
c#代码
public static IList<INote> GetNotes()
{
DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter adapter =
new DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter();
DataSetNoteProcs.up_GetNoteDataTable table =
new DataSetNoteProcs.up_GetNoteDataTable();
IList<INote> notes = new List<INote>();
adapter.Connection = DataAccess.ConnectionSettings.Connection;
adapter.Fill(table);
foreach (DataSetNoteProcs.up_GetNoteRow t in table) {
notes.Add((INote)t);
}
return notes;
}
VB.NET 代码
Public Shared Function GetNotes() As IList(Of INote)
Dim adapter As New DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter
Dim table As New DataSetNoteProcs.up_GetNoteDataTable
Dim notes As IList(Of INote) = New List(Of INote)
adapter.Connection = DataAccess.ConnectionSettings.Connection
adapter.Fill(table)
For Each t As DataSetNoteProcs.up_GetNoteRow In table
notes.Add(CType(t, INote))
Next
Return notes
End Function
推荐答案
不,创建列表并不昂贵.相比于创建数据表并从数据库中取数据,它非常便宜.
No, creating a list is not costly. Compared to creating the data table and fetching the data from the database, it's very cheap.
您可以通过在填充表格后创建列表来降低成本,这样您就可以将初始容量设置为您将放入其中的行数:
You can make it even cheaper by creating the list after populating the table, so that you can set the initial capacity to the number of rows that you will put in it:
IList<INote> notes = new List<INote>(table.Rows.Count);
这篇关于DataTable to List<object>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:DataTable to List<object>
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01