是否有随机列顺序来定义的属性映射CSV代码模式呢? [英] Is there a code pattern for mapping a CSV with random column order to defined properties?

查看:153
本文介绍了是否有随机列顺序来定义的属性映射CSV代码模式呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从各种渠道传递给我的应用程序的CSV。 CSV格式文件的总是有相同数量的列和标头值的列将总是是相同的。

I have a CSV that is delivered to my application from various sources. The CSV will always have the same number columns and the header values for the columns will always be the same.

不过,列可能并不总是以相同的顺序。

However, the columns may not always be in the same order.

第1天CSV可能看起来像这样

ID,FirstName,LastName,Email
1,Johh,Lennon,jlennon@applerecords.com
2,Paul,McCartney,macca@applerecords.com

第2天CSV可能看起来像这样

Email,FirstName,ID,LastName
resident1@friarpark.com,George,3,Harrison
ringo@allstarrband.com,Ringo,4,Starr

我想在标题行中读取每个文件,并有一个简单的机制,对每个与我在类中定义的关联的属性数据栏相关联。

I want to read in the header row for each file and have a simple mechanism for associating each "column" of data with the associated property I have defined in my class.

我知道我可以使用选择语句来弄明白,但这似乎是一个坏的方式来处理它。

I know I can use selection statements to figure it out, but that seems like a "bad" way to handle it.

有一个简单的方法来映射列,以在系统运行时字典或类的属性?

Is there a simple way to map "columns" to properties using a dictionary or class at runtime?

推荐答案

使用字典来映射列标题文本列位置。 。列标题的文本
硬代码映射到对象属性。

Use a Dictionary to map column heading text to column position. Hard-code mapping of column heading text to object property.

例如:

// Parse first line of text to add column heading strings and positions to your dictionary
...

// Parse data row into an array, indexed by column position
...

// Assign data to object properties
x.ID = row[myDictionary["ID"]];
x.FirstName = row[myDictionary["FirstName"]];
...

这篇关于是否有随机列顺序来定义的属性映射CSV代码模式呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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