我在文本/ csv文件中有此数据:
ID,Boo,Soo
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
0,True,qwerty
尤其要注意空白行。我想使用NuGet中的CSVHelper
将此数据读取到多个列表中,其中边界由空白行确定。
因此,如果有一个具有属性MyClass
,ID
和Boo
的类Soo
,并且我直接在代码中初始化上述示例数据,我想要这样的List<List<Mycass>>
:
var data = {
new List<MyClass> {
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} }
},
new List<MyClass> {
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} }
},
new List<MyClass> {
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} }
},
new List<MyClass> {
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} }
},
new List<MyClass> {
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} },
{ new MyClass {ID = 0, Boo = true, Soo = "qwerty"} }
},
}
但是,当然,我不预先知道数据的真实外观。空列表之间的每个列表中可以有任意数量的项目。
这里是我到目前为止的代码:
for (int j = 0; j < rnd.Next(4, 10); j++)
{
for (int i = 0; i < rnd.Next(1, 7); i++)
{
ListMyClass.Add(new MyClass { ID = 0, Boo = true, Soo = "qwerty" });
}
ListListMyClass.Add(new List<MyClass>(ListMyClass));
ListMyClass.Clear();
}
using (var csvWiter = new CsvWriter(new StreamWriter("csvHelper.csv"), CultureInfo.InvariantCulture))
{
foreach (var listRecord in ListListMyClass)
{
csvWiter.WriteRecords(listRecord);
csvWiter.NextRecord();
}
}
我该怎么做?
问题有点令人困惑,但这是您读取数据的方式:
using (var reader = new StreamReader("csvHelper.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var list = csv.GetRecords<MyClass>();
}