【问题标题】:How to fill DataTable column with data from list of struct?如何用结构列表中的数据填充 DataTable 列?
【发布时间】:2014-05-19 12:13:01
【问题描述】:

背景

我有简单的结构:

public struct PostCode
{
    public long itemId;
    public string postCode;

    public PostCode(long id, string code)
    {
        this.itemId = id;
        this.postCode = code;
    }
}

这个结构被用作记录模板。

我用它来存储来自某些网络服务的数据。

我需要将这些代码与已存储在 DataTable 中的数据连接起来。

 DataTable dt = new DataTable();
 dt.Columns.Add(new DataColumn("id", Type.GetType("System.Int32")));
 dt.Columns.Add(new DataColumn("name", Type.GetType("System.String")));
 dt.Columns.Add(new DataColumn("postCode", Type.GetType("System.String")));
 // more columns here

 // getRecords returns datatable but postCode field is empty
 // DataTable dt can contain 100-10000 records
 dt = getRecords(); 

 // preparing list of identifiers (same record count)
 List<long> listOfId = getDataIds(dt);

 // preparing list of identifiers with postal codes
 List<PostCode> codeList = getListOfPostCodes(listOfId);

 // filling postal code field in datatable
 // TODO: code I'm asking for goes here

这不是 SQL 数据库,数据来自 Web 服务,只暴露了几个方法。无法在服务器端加入数据,也无法使用邮政编码查询所有数据。

问题

  1. 如何将我的 List 与 DataTable 对象连接起来?
  2. 也许我应该摆脱这个 PostCode 结构并改用另一个 DataTable?

【问题讨论】:

  • 下面的答案对您有帮助吗,还是您特别需要 C# 2.0 解决方案?

标签: c# c#-2.0


【解决方案1】:
foreach (DataRow d in dt.Rows)
        {
            d["postCode"] = from y in codeList
                             where y.itemId == (int)d["id"]
                             select new { PostCode = y.postCode };
        }

使用快速 linq 语句从列表中填写数据表中的 postCode。另外,id 一方面是 long,另一方面是 int,如果它存储类似的数据,则应保持大小相同。

【讨论】:

  • 此答案使用 LINQ,但问题标记为 c#-2.0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
相关资源
最近更新 更多