Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A snippet that converts a List of objects to a DataTable

NotificationsYou must be signed in to change notification settings

RobinKim-SWEngineer/C-Sharp-snippet-ListToDataTableConverter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 

Repository files navigation

Image

ListToDataTable Converter

What is this snippet about ?

This is a code snippet that can converta list of data types to a data table. This conversion is necessary when we need to export the query result into a excel file because when working with Database, we get the data set from DB as a list of model objects.

When it comes to working with database, Dapper is a handy library that does relational mapping for us between C# object <--> Query result, which reduces the amount of code dramatically.

How this snippet is written ?

  1. Getting property value fromobject type using System.Reflection

    • First we need to gettype out of object and obtainpropery from that type

    • When getting type, we do either bytypeof(T) orobj.GetType(), assuming that the argument is passed to Converter() method asList<T> listOfObjects.

    • Once we get type of the object, we apply either.GetProperties(), which returns an array of all properties included inside the typeor.GetProperty(string propName) and further.GetValue(object obj).

  2. Putting into DataTable

    • For title row, we loop throughtypeof(T).GetProperties() and apply.Nameupon each property.

    • For content rows, the process is same but two loos are required. Outer one loops throughlist Of Objects while inner one loops throughproperties in each object.

    • Upon each loop of a object, a row is added to DataTable using.Add(DataRow row)

About

A snippet that converts a List of objects to a DataTable

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp