简体   繁体   English

将一般列表/可枚举DataRow添加到DataTable?

[英]Add a Generic List/Enumerable DataRow to DataTable?

I am trying to write a function which takes generic List/Enumerable and add DataRow to existing DataTable but only for Custom Columns. 我正在尝试编写一个函数,该函数采用通用List / Enumerable并将DataRow添加到现有DataTable,但仅用于自定义列。

public void AddGridRow<T>(IEnumerable<T> rowData, params String[] columnNames)
{
  HashSet<String> columnsHashSet = new HashSet<String>(columnNames);

  PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
  foreach (T item in rowData)
  {
      foreach (PropertyDescriptor prop in properties)
      {
         foreach (DataColumn column in _dataGridTable.Columns)
         {
             DataRow newRow = _dataGridTable.NewRow();
             if (columnsHashSet.Contains(prop.Name))
             {
                 newRow[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                 _dataGridTable.Rows.Add(newRow); // _dataGridTable is my existing DataTable
                break;
             }
          }
       }
   }
}

Now the problem is it is not behaving correctly, lets say I have to add 1 row in 4 columns (columnNames), it is adding the 1 Row per columns. 现在问题是它的行为不正确,假设我必须在4列(columnNames)中添加1行,它每列添加1行。 Also there are far many foreach loops. 还有很多foreach循环。 How can I correct this and if possible optimize it. 我该如何纠正这一点,如果可能的话,优化它。

You need to move the "_dataGridTable.Rows.Add(newRow);" 你需要移动“_dataGridTable.Rows.Add(newRow);” line outside of the inner foreach loop: 内部foreach循环之外的行:

foreach (T item in rowData)
  {
      foreach (PropertyDescriptor prop in properties)
      {
         DataRow newRow = _dataGridTable.NewRow();
         foreach (DataColumn column in _dataGridTable.Columns)
         {
             if (columnsHashSet.Contains(prop.Name))
             {
                 newRow[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                break;
             }
          }
       }
      _dataGridTable.Rows.Add(newRow); // _dataGridTable is my existing DataTable
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM