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

如何将SQL数据库查询结果转换为C#自定义类对象列表?

将DataTable转换为C#自定义类对象列表的方法

首先,你需要创建与agents表结构匹配的自定义C#类,属性名建议和SQL列名保持一致(也可以手动指定映射关系):

public class Agent
{
    public int AgentId { get; set; }
    public string Name { get; set; }
    public string? Email { get; set; }
    // 根据你的agents表实际列,添加对应属性,注意数据类型匹配
}

方法一:手动遍历DataTable完成映射(基础实现)

你可以遍历DataTable的每一行,把列值逐一赋值给自定义类的属性,最终收集为列表:

List<Agent> agentList = new List<Agent>();
foreach (DataRow row in table.Rows)
{
    Agent agent = new Agent
    {
        AgentId = Convert.ToInt32(row["AgentId"]),
        Name = row["Name"].ToString(),
        Email = row.IsNull("Email") ? null : row["Email"].ToString()
        // 处理其他列时注意判断DBNull,避免空引用异常
    };
    agentList.Add(agent);
}

也可以用LINQ写法简化代码:

List<Agent> agentList = table.AsEnumerable()
    .Select(row => new Agent
    {
        AgentId = row.Field<int>("AgentId"),
        Name = row.Field<string>("Name"),
        Email = row.Field<string?>("Email") // 可空类型会自动处理DBNull
    })
    .ToList();

提示:Field<T>方法会自动处理DBNull值,如果列允许为空,记得使用可空值类型(如string?、int?)。

方法二:跳过DataTable,直接查询为对象列表(更高效)

其实不需要先填充DataTable,可以用ORM工具(比如Dapper)直接从数据库查询出对象列表,代码更简洁高效:

  1. 先通过NuGet包管理器安装Dapper
  2. 使用以下代码查询:
using (var con = new SqlConnection(@"Data Source=xxxxxxxxx;Initial Catalog=Person.costumer;integrated security=true"))
{
    con.Open();
    string selectQuery = "select * from agents";
    List<Agent> agentList = con.Query<Agent>(selectQuery).ToList();
}

Dapper会自动完成SQL列和类属性的映射,无需手动处理每一列。

为什么直接用ToList()不行?

DataTable的Rows集合是DataRow类型的集合,和你的自定义Agent类型不兼容,必须显式完成属性的映射转换,才能得到目标类型的列表。

内容的提问来源于stack exchange,提问作者נחמה לובלינג

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 20:52:09