如何用结构列表中的数据填充DataTable列
本文关键字:数据 填充 DataTable 何用 结构 列表 | 更新日期: 2023-09-27 18:04:07
背景
我有一个简单的结构:
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服务,只有少数方法被公开。不可能在服务器端连接数据,也不可能用邮政编码查询所有数据。
问题
- 如何将列表与DataTable对象连接
- 也许我应该去掉这个PostCode结构,转而使用另一个DataTable
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,如果它存储类似的数据,则应该保持大小相同。