C#Linq至CSV动态对象运行时列名称 [英] C# Linq to CSV Dynamic Object runtime column name
问题描述
我是C#中动态对象的新手。我正在读取CSV文件,其内容与此处的代码非常相似: http://my.safaribooksonline.com/book/programming/csharp/9780321637208/csharp-4dot0-features/ch08lev1sec3
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.
例如,我有:
var records = from r in myDynamicClass.Records select r;
foreach(dynamic rec in records)
{
Console.WriteLine(rec.SomeColumn);
}
如果您知道 SomeColumn名称,此方法就很好。我希望有一个列名aa字符串,并能够在运行时刷新相同的类型。
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.
推荐答案
必须创建一个继承自 DynamicObject
的类,只需在该类中添加一个索引器即可通过字符串获得结果。
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.
下面的示例使用在书示例中找到的 same 属性,该属性保存具有该列的单个行数据名称。下面是该类的索引器,以实现结果:
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;
}
}
}
然后访问数据,例如
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.
这篇关于C#Linq至CSV动态对象运行时列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!