2016-05-13 15 views
1

我試圖用擴展方法將List轉換爲datatable。實施是:名爲'Item'的列已經屬於此DataTable

擴展方法

public static class list2Dt 
    { 
     public static DataTable ToDataTable<T>(List<T> items) 
     { 
      DataTable dataTable = new DataTable(typeof(T).Name); 

      //Get all the properties 
      PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 
      foreach (PropertyInfo prop in Props) 
      { 
       //Setting column names as Property names 
       dataTable.Columns.Add(prop.Name); 
      } 
      foreach (T item in items) 
      { 
       var values = new object[Props.Length]; 
       for (int i = 0; i < Props.Length; i++) 
       { 
        //inserting property values to datatable rows 
        values[i] = Props[i].GetValue(item, null); 
       } 
       dataTable.Rows.Add(values); 
      } 
      //put a breakpoint here and check datatable 
      return dataTable; 
     } 
    } 

控制器

var noDups = firstTable.AsEnumerable() 
          .GroupBy(d => new 
          { 
           name = d.Field<string>("name"), 
           date = d.Field<string>("date") 
          }) 
          .Where(d => d.Count() > 1) 
          .Select(d => d.First()) 
          .ToList(); 

         DataTable secondTable = new DataTable(); 
         secondTable.Columns.Add("name", typeof(string)); 
         secondTable.Columns.Add("date", typeof(string)); 
         secondTable.Columns.Add("clockIn", typeof(string)); 
         secondTable.Columns.Add("clockOut", typeof(string)); 

         secondTable = list2Dt.ToDataTable(noDups); 

我得到這個以下錯誤:

An exception of type 'System.Data.DuplicateNameException' occurred in System.Data.dll but was not handled in user code 

Additional information: A column named 'Item' already belongs to this DataTable. 

上述錯誤引發在線:

dataTable.Columns.Add(prop.Name); 

有人可以找到問題所在。

+0

你的問題是你已經添加了4列到你的數據表中,然後調用toDataTable它試圖添加所有列 – BugFinder

+1

@BugFinder這不是問題在這種情況下,但它是沒有意義的,因爲OP然後通過調用它下面的'ToDataTable'將它拋出。 – Jamiec

+0

我錯過了 - 好點 – BugFinder

回答

2

您的ToDataTable方法需要一個對象列表 - 很可能是簡單的DTO或類似列表。

你傳遞DataRow實例,其中的那類有多個overloads of property Item這意味着,當你試圖建立一個列表中的新DataTable它會嘗試與名稱Item這是無效的添加多個列DataTable

圍繞這種方式對於項目noDups到一個新的對象,而不是保留DataRow

public class MyClass 
{ 
    public string Name{get;set;} 
    public string Date{get;set;} 
} 

var noDups = firstTable.AsEnumerable() 
         .GroupBy(d => new 
         { 
          name = d.Field<string>("name"), 
          date = d.Field<string>("date") 
         }) 
         .Where(d => d.Count() > 1) 
         .Select(d => { 
           var first = d.First(); 
           return new MyClass() 
           { 
            Name = (string)first["name"], 
            Date = (string)first["date"] 
           } 
         }) 

         .ToList(); 
+0

接下來應該做什麼? – Jogi

+0

@RehanKhan查看更新 – Jamiec

+0

良好的工作。雖然它給了我正確的輸出,但我仍然困惑於「哪個類有多個屬性Item的重載,這意味着當你試圖建立新的DataTable時,它會嘗試添加多個名字爲Item的列在DataTable中無效「。 – Jogi

相關問題