5

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!

2 Answers 2

7

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>?

Sign up to request clarification or add additional context in comments.

2 Comments

Do you know if the ExpandoObject would support intellisense? Say I return an ExpandoObject based on a Dictionary, would that object support intellisense so I can see the property names suggested?
@Joze: Not at compile-time, no. I believe there's debugger support though.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.