You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中无名称DataTable转List作为DataGrid数据源及优化

解决方案

一、VB.NET 实现无名称DataTable转List

不管DataTable是否命名,都可以用以下两种通用方式完成转换:

1. 转换为List(Of Dictionary(Of String, Object))

无需预先定义实体类,直接按列名和对应值存储,适合不确定DataTable结构的场景:

Imports System.Data

Public Function DataTableToDictionaryList(dt As DataTable) As List(Of Dictionary(Of String, Object))
    Dim dictList As New List(Of Dictionary(Of String, Object))()
    For Each row As DataRow In dt.Rows
        Dim dict As New Dictionary(Of String, Object)()
        For Each col As DataColumn In dt.Columns
            dict.Add(col.ColumnName, row(col))
        Next
        dictList.Add(dict)
    Next
    Return dictList
End Function

' 使用示例
Dim xDt As New DataTable
' 假设已完成xDt的数据填充
Dim dataList = DataTableToDictionaryList(xDt)
DataGrid1.ItemsSource = dataList

2. 转换为指定实体类的List(已知数据结构时)

如果清楚DataTable列对应实体类的属性,可以用反射实现强类型转换:

Imports System.Data
Imports System.Reflection

Public Function DataTableToEntityList(Of T As {New})(dt As DataTable) As List(Of T)
    Dim entityList As New List(Of T)()
    Dim props As PropertyInfo() = GetType(T).GetProperties()
    
    For Each row As DataRow In dt.Rows
        Dim entity As New T()
        For Each prop As PropertyInfo In props
            If dt.Columns.Contains(prop.Name) AndAlso row(prop.Name) IsNot DBNull.Value Then
                prop.SetValue(entity, Convert.ChangeType(row(prop.Name), prop.PropertyType))
            End If
        Next
        entityList.Add(entity)
    Next
    Return entityList
End Function

' 使用示例:先定义对应实体类
Public Class MyDataEntity
    Public Property Id As Integer
    Public Property Name As String
    ' 其他属性与DataTable列一一对应
End Class

' 转换并绑定数据源
Dim dataList = DataTableToEntityList(Of MyDataEntity)(xDt)
DataGrid1.ItemsSource = dataList

二、更高效的DataGrid数据源优化方案

大数量数据直接绑定卡顿的核心原因是DataGrid默认一次性渲染所有行,以下是针对性优化方案:

  • 开启UI虚拟化:WPF的DataGrid默认支持虚拟化,但如果嵌套在ScrollViewer中会失效,确保DataGrid直接置于容器内,或显式配置:

    <DataGrid VirtualizingStackPanel.IsVirtualizing="True"
              VirtualizingStackPanel.VirtualizationMode="Recycling"/>
    

    虚拟化仅渲染当前可见区域的行,大幅降低内存占用与渲染耗时。

  • 直接使用DataView:DataTable的DefaultView是轻量级视图,支持排序、筛选,性能优于转List,配合虚拟化使用效果更佳:

    DataGrid1.ItemsSource = xDt.DefaultView
    
  • 分页加载数据:针对超大量数据,采用分页策略,每次仅加载当前页的50-100条数据,用户翻页时再加载对应页内容,彻底避免一次性加载全量数据。

  • 使用BindingList(Of T):若需数据变更自动同步UI,BindingList(Of T)比普通List更适配,它实现了IBindingList接口,性能优于直接绑定DataTable。


内容的提问来源于stack exchange,提问作者M.J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:50:29