Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

c# - LINQ to map a datatable into a list<MyObject>

I just discover LINQ so be comprehensive with me please! :-)

So! I have a Data-tier who provide me datatables and i want to convert them into lists of objects. These objects are defined in a spécific layer DTO (Data transfer Objects).

How can I map every rows of my datatable into objects and put the all objects into a list? (today i make it "manually" field after field) Is it possible with LINQ? I've heard about LINQ2Entities? am i right?

Thanks to help a beginner to understand...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the objects is not too complex you can use this:

public static class DataTableExtensions
{
   public static IList<T> ToList<T>(this DataTable table) where T : new()
   {
      IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
      IList<T> result = new List<T>();

      foreach (var row in table.Rows)
      {
         var item = CreateItemFromRow<T>((DataRow)row, properties);
         result.Add(item);
      }

      return result;
   }

   private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
   {
       T item = new T();
       foreach (var property in properties)
       {
           property.SetValue(item, row[property.Name], null);
       }
       return item;
   }
}

With that in place you can now write: var list = YourDataTable.ToList<YourEntityType>().

You can read about it here: http://blog.tomasjansson.com/convert-datatable-to-generic-list-extension/

And it is an answer to a previous question: Convert DataTable to Generic List in C#

EDIT: I should add that this is not linq, but some extension methods to DataTable I wrote. Also, it is working with the convention that the properties in the object you're mapping with has the same name as in the DataTable. Of course this could be extended to read attributes on the properties or the method itself could take a simple Dictionary<string,string> that could be used to do the mapping. You could also extend it with some functionality that take a params string[] excludeProperties that could be used to exclude some of the properties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...