DataTable to List<object>

DataTable to Listlt;objectgt;(DataTable to Listlt;objectgt;)
本文介绍了DataTable to List<object>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)