C # Linq to CSV Dynamic Object runtime column name

I am new to using dynamic objects in C #. I read the CSV file very similar to the code found here: http://my.safaribooksonline.com/book/programming/csharp/9780321637208/csharp-4dot0-features/ch08lev1sec3

I can reference the data I need with a static name, however I cannot find the correct syntax for the link using the dynamic name at run time.

For example, I have:

var records = from r in myDynamicClass.Records select r;

foreach(dynamic rec in records)
{
     Console.WriteLine(rec.SomeColumn);
}

And this works great if you know the name "SomeColumn". I would prefer the column name to be a string and that at run time a repetition of the same type be done.

+2
3

, DynamicObject, .

, , , , . :

public class myDynamicClassDataLine : System.Dynamic.DynamicObject
{ 
   string[] _lineContent; // Actual line data
   List<string> _headers; // Associated headers (properties)

   public string this[string indexer]
   {
      get 
      {
         string result = string.Empty;
         int index = _headers.IndexOf(indexer);

         if (index >= 0 && index < _lineContent.Length)
            result = _lineContent[index];

         return result;
      }

  }
}

,

var csv = 
@",,SomeColumn,,,
ab,cd,ef,,,";  // Ef is the "SomeColumn"

var data = new myDynamicClass(csv); // This holds multiple myDynamicClassDataLine items

Console.WriteLine (data.OfType<dynamic>().First()["SomeColumn"]); // "ef" is the output.
+3

. , :

List<string> columnNames = new List<string>(records.GetType().GetProperties().Select(i => i.Name));

:

foreach(dynamic rec in records)
{
    foreach (string prop in columnNames)
         Console.Write(rec.GetType().GetProperty (prop).GetValue (rec, null));

}
+1

string column = "SomeColumn";
var result = rec.GetType().GetProperty (column).GetValue (rec, null);
0

All Articles