问题描述
到目前为止,我有一款非常好用的
private static MovieItem readCSV(string path)
{
var yourData = File.ReadAllLines(path)
.Skip(1)
.Select(x => x.Split(';'))
.Select(x => new Movie
{
GUID = x[0],Title = x[1],ISBN = x[2],CreatedTime = DateTime.Now,Authorinformation = new Authorinformation()
{
Id = Guid.NewGuid().ToString(),Name = x[4],Address = x[5],Age = x[6]
}
}).ToArray();
return yourData[0];
}
我的问题是,是否有更好的方法分配对象?
到目前为止,我喜欢GUID = x[0],Title = x[1]
等等……这不好,因为第一行的标题可以更改,所以我想保持灵活性。
有没有办法分配例如GUID到名为GUID的CSV标头中?
就像寻找标题名称,如果它等于GUID,将内容分配给GUID吗?
CSV文件:
解决方法
我已经评论了您的问题,但这是示例代码:
1-创建一个班级,并将其命名为“ Book”或其他方便的名称。它的字段是GUID,标题,ISBN等。
public class Book //I'm showing only one field of the class
{
private string title;
public string Title { get; set;}
public Book() {}
}
2-一次性读取CSV文件,您将仅读取第一行并将其拆分为字符串[]数组-您的拆分器为“;”-,并将每个字段的索引存储到变量中(Switch语句为这里很有帮助)
public struct Headers //use it to store the index of each field in the file only title is shown here
{
public int title;
}
string[] rowSplitter = new string[] { "\r\n" };
string[] colSplitter = new string[] { ";" };
//Inside a method for reading the file use the following code
string[] csvData = File.ReadAllText(csvFile).Split(rowSplitter,StringSplitOptions.RemoveEmptyEntries);
string[] headerRow = csvData [0].Split(colSplitter,StringSplitOptions.None);
Headers column = new Headers();
for (int i = 0; i < headerRow.Length; i++)
{
switch (headerRow[i].ToLower())
{
case "title":
column.title = i;
break;
}
}
3-使用循环遍历所有行,用“;”分隔再次,在此循环中,实例化具有相应数据cuz的Book()对象,现在您知道每个数据项的索引-我提到的变量。
for (int i = 1; i < csvData.Length; i++)
{
string[] currentRow = csvData[i].Split(colSplitter,StringSplitOptions.None);
Book bookItem = new Book();
bookItem.Title = currentRow[column.title];
//Here you can do whatever you like with this bookItem on-the-fly or if you want to keep it to the end of your code add it to a list.
}
,
//reading all the lines(rows) from the file.
string[] rows = File.ReadAllLines(Directory.GetFiles(@"D:\CSV\test.csv"));
DataTable dtData = new DataTable();
string[] rowValues = null;
DataRow dr = dtData.NewRow();
//Creating columns
if (rows.Length > 0)
{
foreach (string columnName in rows[0].Split(','))
dtData.Columns.Add(columnName.Replace(" ","").ToLower());
}
//Creating row for each line.(except the first line,which contain column names)
for (int row = 1; row < rows.Length; row++)
{
rowValues = rows[row].Split(',');
dr = dtData.NewRow();
dr.ItemArray = rowValues;
dtData.Rows.Add(dr);
}