问题描述
如何获取 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>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!