(de)从CSV序列化到一个对象(或最好是一个对象类型的列表) [英] (de)Serialize from CSV to an object (or preferably a list of type object)
问题描述
(我是一个C ++程序员 - 试图学习C#,它似乎有一些内置对象序列化 - 但我有点离开这里...)
(I am a C++ programmer - trying to learn C# - and it appears that there are some built in object serialization - but I am a bit out of water here...)
我被要求从CSV文件中将测试数据加载到对象集合中。 (CSV比xml优先,因为它对人类来说是一个简单易读的东西,我们创建测试数据来运行单元测试)
I have been asked to load test data into a collection of objects from a CSV file. (CSV is preferred over xml because it is a heck of a lot simpler and readable to humans. We are createing test data to run unit tests)
集合将是一个(简单)对象的列表。
The collection will be a list of (simple) objects.
List<MyObject>
其中MyObject是一个包含几个双精度和几个整数的类。
Where MyObject is a class that contains a few doubles and a few ints.
这样做的首选方法是什么?我不认为我会需要序列化这些对象中的一个。
What is the preferred way to do this? I don't think I will ever have a need to serialize just one of these objects.
我希望一行代表一个对象,一组行
I would expect that one single line represents one object, and the set of lines in the file is used to make the list/collection.
推荐答案
下面应该做的伎俩,只是这几个月前
Below should do the trick, just did this a couple months ago for data conversion project i was working on.
对于任何进行CSV(或任何字符分隔字符串)的人来说,一个主要注意事项,你真的应该看看使用特定的库它。
A major note to anyone doing CSV (or any character delimited strings), you really should look at using a specific library suited for it. The most popular one I've found is below (pretty tried and true)
你会从 string.Split(',')开始。
然后当有人不小心在你的测试数据文件中抛出一个逗号时,你做什么? ...这只是噩梦之后的噩梦,这个图书馆已经遍历了你的大部分:
You'll start with string.Split(',')
and then what do you do when someone accidentally throws a comma in your test data file? ... it's just nightmare after nightmare and this library has traversed most of that for you:
http://www.codeproject.com/KB/database/CsvReader.aspx?msg=3227161
using System.IO;
using LumenWorks.Framework.IO.Csv;
static class Program
{
public class MyObject
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
public decimal Prop3 { get; set; }
}
void ReadCsv()
{
//holds the property mappings
Dictionary<string, int> myObjectMap = new Dictionary<string, int>();
List<MyObject> myObjectList = new List<MyObject>();
// open the file "data.csv" which is a CSV file with headers
using (CsvReader csv = new CsvReader(new StreamReader("data.csv"), true))
{
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
for (int i = 0; i < fieldCount; i++)
{
myObjectMap[headers[i]] = i; // track the index of each column name
}
while (csv.ReadNextRecord())
{
MyObject myObj = new MyObject();
myObj.Prop1 = csv[myObjectMap["Prop1"]];
myObj.Prop2 = csv[myObjectMap["Prop2"]];
myObj.Prop3 = csv[myObjectMap["Prop3"]];
myObjectList.Add(myObj);
}
}
}
}
这篇关于(de)从CSV序列化到一个对象(或最好是一个对象类型的列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!