如何获取DataTable并将其转换为List?
我在C#和VB.NET中都包含了一些代码,这两个问题都是我们创建一个新对象来返回数据,这是非常昂贵的.我需要返回对象的引用.
DataSetNoteProcsTableAdapters.up_GetNoteRow对象确实实现了INote接口.
我正在使用ADO.NET和.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;
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我有另一种方法可能值得一看.这是一种帮助方法.创建名为CollectionHelper的自定义类文件:
public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
return null;
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
rows.Add(row);
return ConvertTo<T>(rows);
}
Run Code Online (Sandbox Code Playgroud)
想象一下,你想获得一份客户名单.现在您将拥有以下来电者:
List<Customer> myList = (List<Customer>)CollectionHelper.ConvertTo<Customer>(table);
Run Code Online (Sandbox Code Playgroud)
您在DataTable中拥有的属性必须与您的Customer类(名称,地址,电话等字段)匹配.
我希望它有所帮助!
谁愿意知道为什么要使用列表而不是DataTables:链接文本
完整样本:
不,创建列表并不昂贵。与创建数据表并从数据库中获取数据相比,它非常便宜。
您可以通过在填充表后创建列表来使其更便宜,以便您可以将初始容量设置为要放入其中的行数:
IList<INote> notes = new List<INote>(table.Rows.Count);
Run Code Online (Sandbox Code Playgroud)