C# Linq to CSV 动态对象运行时列名 [英] C# Linq to CSV Dynamic Object runtime column name

查看:20
本文介绍了C# Linq to CSV 动态对象运行时列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是在 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"名称,这将正常工作.我更喜欢有一个字符串的列名,并且能够在运行时进行相同的类型引用.

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.

以下示例使用了本书示例中的相同属性,这些属性包含具有列名的单个行数据.以下是该类的索引器以实现结果:

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 to CSV 动态对象运行时列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆