How to convert a Dictionary<ID, AList>) into a DataTable using C#

Josh S 26 Reputation points
2023-12-11T05:07:03.5633333+00:00

I have a Dictionary<ID(long int), AList>), AList is a collection of type AList object.

A description of what is behind the scene of the dictionary data structure:

Alist object is something like Column1, Column2,……..,Column150 with their respective values.

This is a row in an Access Table that has a unique ID (row ID), and 150 columns. This columns data types are varchar, long integer, double etc.

The dictionary is an Ordered Dictionary

How do I convert the dictionary into a data table? How do I add each column appropriate data type in the data table?

I search Microsoft, stack overflow, iTechNote, Code Project but have not found a dialogue or solution that matches my requirements. It is my work related project and I have 15 days to complete.  My company is will not extend time.

Your assistance will be monumental help. 

Thank you.

Developer technologies | .NET | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 78,086 Reputation points Volunteer Moderator
    2023-12-11T17:18:48.4+00:00

    you need to create a dateable with columns that match your object. then loop thru the dictionary and add a row to data table.

    		// create table and get obj types
    		var table = new DataTable();
            var props = dictionary
    			.GetType()
    			.GetGenericArguments()[1]
    			.GetProperties(BindingFlags.Instance|BindingFlags.Public);
    				
    		// define columns
    		foreach (var p in props)
    		{
    			table.Columns.Add(p.Name, p.PropertyType);
    		}
    		
    		// copy data
    		foreach (var obj in dictionary)
    		{
    			// new row
    			var row = table.NewRow();
    
    			// copy column values
    			foreach (var p in props)
    			{
    				row[p.Name] = p.GetValue(obj);
    			}
    
    			// add row to table
    			table.Rows.Add(row);
    		}
    		
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.