C# Linq to CSV Dynamic Object runtime column name

帅比萌擦擦* 提交于 2020-01-02 15:09:36

问题


I'm new to using Dynamic Objects in C#. I am reading a CSV file very similarly 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 can not find the correct syntax to reference using a 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 fine if you know the "SomeColumn" name. I would prefer to have a column name a a string and be able to make the same type refrence at run time.


回答1:


Since one has to create the class which inherits from DynamicObject, simply add an indexer to the class to achieve one's result via strings.

The following example uses the same properties found in the book example, the properties which holds the individual line data that has the column names. Below is the indexer on that class to achieve the result:

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;
      }

  }
}

Then access the data such as

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.



回答2:


You will need to use reflection. To get the names you would use:

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

You can then loop through your results and output the values for each column like so:

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

}



回答3:


Try this

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


来源:https://stackoverflow.com/questions/22024492/c-sharp-linq-to-csv-dynamic-object-runtime-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!