【问题标题】:Populate DataTable with LINQ in C#在 C# 中使用 LINQ 填充 DataTable
【发布时间】:2009-09-10 12:32:23
【问题描述】:

我的应用中有一个方法使用以下代码填充 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 实现相同的功能,以便稍微缩短此代码。有什么想法吗?

【问题讨论】:

  • 你用数据表做什么?是用于数据库插入吗?
  • 我没有使用数据库。这是为了填充列表框数据源。

标签: c# linq datatable


【解决方案1】:

是的,简单

    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 列相同。

【讨论】:

    【解决方案2】:

    好吧,这段代码不是更短或 Linq,但我做了一个外部方法,它接受一个 IList 并将其转换为一个 DataTable 给你。

        public static DataTable ToDataTable<T>(this IList<T> theList)
        {
            DataTable theTable = CreateTable<T>();
            Type theEntityType = typeof(T);
    
            // Use reflection to get the properties of the generic type (T)
            PropertyDescriptorCollection theProperties = TypeDescriptor.GetProperties(theEntityType);
    
            // Loop through each generic item in the list
            foreach (T theItem in theList)
            {
                DataRow theRow = theTable.NewRow();
    
                // Loop through all the properties
                foreach (PropertyDescriptor theProperty in theProperties)
                {
                    // Retrieve the value and check to see if it is null
                    object thePropertyValue = theProperty.GetValue(theItem);
                    if (null == thePropertyValue)
                    {
                        // The value is null, so we need special treatment, because a DataTable does not like null, but is okay with DBNull.Value
                        theRow[theProperty.Name] = DBNull.Value;
                    }
                    else
                    {
                        // No problem, just slap the value in
                        theRow[theProperty.Name] = theProperty.GetValue(theItem);
                    }
                }
    
                theTable.Rows.Add(theRow);
            }
    
            return theTable;
        }
    

    【讨论】:

      【解决方案3】:

      您首先确定是否可以查询this.mailItem.Attachments和 如果可能的话,您可以将查询结果从Steve Sloka创建的扩展方法转换为数据表...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-24
        • 2013-02-19
        • 1970-01-01
        • 2013-03-05
        • 2017-12-19
        • 1970-01-01
        • 2010-09-20
        • 1970-01-01
        相关资源
        最近更新 更多