gpt4 book ai didi

c# - 在 C# 中使用 LINQ 填充 DataTable

转载 作者:太空宇宙 更新时间:2023-11-03 11:53:28 24 4
gpt4 key购买 nike

我的应用程序中有一个方法可以使用以下代码用数据填充 DataTable:

DataTable dt = this.attachmentsDataSet.Tables["Attachments"];

foreach (Outlook.Attachment attachment in this.mailItem.Attachments)
{
DataRow dr = dt.NewRow();
dr["Index"] = attachment.Index;
dr["DisplayName"] = String.Format(
CultureInfo.InvariantCulture,
"{0} ({1})",
attachment.FileName,
FormatSize(attachment.Size));
dr["Name"] = attachment.FileName;
dr["Size"] = attachment.Size;

dt.Rows.Add(dr);
}

我想知道我是否可以使用 LINQ 实现相同的功能以稍微缩短这段代码。有什么想法吗?

最佳答案

是的,很简单

    public void FillFromList(List<T> col)
{
Type elementType = typeof(T);

// Nested query of generic element list of property
// values (using a join to the DataTable columns)
var rows = from row in col
select new
{
Fields = from column in m_dataTable.Columns.Cast<DataColumn>()
join prop in elementType.GetProperties()
on column.Caption equals prop.Name
select prop.GetValue(row, null)
};

// Add each row to the DataTable
int recordCount = 0;
foreach ( var entry in rows )
{
m_dataTable.Rows.Add(entry.Fields.ToArray());
}

这假定 T 上的属性与 DataTable 列相同。

关于c# - 在 C# 中使用 LINQ 填充 DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1405018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com