Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object with dynamic properties in C#

I'm using linq to load a csv file, but because the csv may have any number of columns, the object that it returns will need dynamic properties, and I can't figure out how to do that.

var data = from row in csvData
       let col = row.Split(',')
       select new
              {
                  Field1 = data[0],
                  Field2 = data[1],
                  Field3 = data[2] // etc, etc
              };

If possible, I'd like to name the properties by the name given in the csv file, rather than field1, field2, etc.

Thanks!

like image 822
Greg Avatar asked Aug 26 '10 11:08

Greg


People also ask

How do you create a dynamic object?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.

How do you create a dynamic object in C++?

A dynamic object is created using a "new" operator that returns a pointer to the newly constructed object and is destructed by a "delete" operator. A pointer variable is used to hold the pointer to the object that is returned by the "new" operator.

Why do we use dynamic objects?

Reference to Dynamic Objects in C++ C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically.


2 Answers

What would you do with this afterwards? If you know the names elsewhere and you're using .NET 4, you could use ExpandoObject - populate it by using it as a dictionary, and then access the property names using dynamic typing later. But if it's all dynamic (i.e. you don't know anything statically anywhere), why don't you just use Dictionary<string, string>?

like image 157
Jon Skeet Avatar answered Sep 21 '22 14:09

Jon Skeet


You could just do is simply using arrays or even a Dictionary but if you want to do something cool with Dynamic check out Clay

http://weblogs.asp.net/bleroy/archive/2010/08/18/clay-malleable-c-dynamic-objects-part-2.aspx

like image 23
Sruly Avatar answered Sep 23 '22 14:09

Sruly