数据表中列出&LT;对象&gt; [英] DataTable to List<object>
问题描述
如何获取DataTable并将其转换为一个列表?
我已经包括在以下C#和VB.NET一些code,与这两个问题是,我们创建了一个新的对象返回数据,这是非常昂贵的。我需要返回到对象的引用。
该DataSetNoteProcsTableAdapters.up_GetNoteRow对象确实实现了INote接口。
我使用ADO.NET,以及.NET 3.5
C#code
公共静态的IList&LT; INote&GT; GetNotes()
{
DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter适配器=
新DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter();
DataSetNoteProcs.up_GetNoteDataTable表=
新DataSetNoteProcs.up_GetNoteDataTable(); IList的&LT; INote&GT;注释=新的List&LT; INote&GT;(); adapter.Connection = DataAccess.ConnectionSettings.Connection;
adapter.Fill(表); 的foreach(DataSetNoteProcs.up_GetNoteRow吨表){
notes.Add((INote)T);
} 返回说明;
}
VB.NET code
公共共享功能GetNotes()作为IList的(中INote)
昏暗的适配器作为新DataSetNoteProcsTableAdapters.up_GetNoteTableAdapter
昏暗的表作为新DataSetNoteProcs.up_GetNoteDataTable 昏暗的笔记的IList(中INote)=新名单(中INote) adapter.Connection = DataAccess.ConnectionSettings.Connection
adapter.Fill(表) 对于每一个T作为DataSetNoteProcs.up_GetNoteRow在表
notes.Add(CTYPE(T,INote))
下一个 返回笔记
结束功能
没有,创建列表并不昂贵。相比于创建数据表,并从数据库中获取数据,这是很便宜的。
您可以填充表后使其更通过创建列表便宜,这样就可以设置初始容量的行数,你就会把它:
的IList&LT; INote&GT;注释=新的List&LT; INote&GT;(table.Rows.Count);
How do I take a DataTable and convert it to a List?
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.
The DataSetNoteProcsTableAdapters.up_GetNoteRow object does implement the INote interface.
I am using ADO.NET, along with .NET 3.5
c# code
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 Code
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);
这篇关于数据表中列出&LT;对象&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!