gpt4 book ai didi

c# - 要列出的数据表
转载 作者:太空狗 更新时间:2023-10-29 20:15:33 24 4
gpt4 key购买 nike

如何获取 DataTable 并将其转换为 List?

我在 C# 和 VB.NET 中包含了一些代码,这两个的问题是我们创建了一个新对象来返回数据,这是非常昂贵的。我需要返回对该对象的引用。

DataSetNoteProcsTableAdapters.up_GetNoteRow 对象确实实现了 INote 接口(interface)。

我正在使用 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;
}

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

最佳答案

我有另一种方法可能值得一看。这是一个辅助方法。创建一个名为 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);
}

假设您想获得一份客户名单。现在您将有以下来电者:

List<Customer> myList = (List<Customer>)CollectionHelper.ConvertTo<Customer>(table);

DataTable 中的属性必须与您的客户类相匹配(姓名、地址、电话等字段)。

希望对您有所帮助!

对于愿意知道为什么使用列表而不是数据表的人:link text

完整示例:

http://lozanotek.com/blog/archive/2007/05/09/Converting_Custom_Collections_To_and_From_DataTable.aspx

关于c# - 要列出的数据表<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/709035/

24 4 0