Convert generic List/Enumerable to DataTable?

后端 未结 27 2151
臣服心动
臣服心动 2020-11-21 23:20

I have few methods that returns different Generic Lists.

Exists in .net any class static method or whatever to convert any list into a datatable? The only thing tha

27条回答
  •  鱼传尺愫
    2020-11-22 00:02

    This link on MSDN is worth a visit: How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

    This adds an extension method that lets you do this:

    // Create a sequence. 
    Item[] items = new Item[] 
    { new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"}, 
      new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
      new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
      new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};
    
    // Query for items with price greater than 9.99.
    var query = from i in items
                 where i.Price > 9.99
                 orderby i.Price
                 select i;
    
    // Load the query results into new DataTable.
    DataTable table = query.CopyToDataTable();
    

提交回复
热议问题