[英]Reading CSV file And Show Data
I'm bit puzzle with some basic and now I decided that I should take help.我对一些基本的东西有点困惑,现在我决定我应该寻求帮助。 I have simple.csv file with following data:
我有 simple.csv 文件,其中包含以下数据:
And I need following output:我需要关注 output:
I have already done it but in my coding, I'm reading column name with hardcoding.我已经完成了,但在我的编码中,我正在使用硬编码读取列名。 This will cause issue if column will change their position like below:
如果列将更改其 position 如下所示,这将导致问题:
I think this can be done easily using for loop but I'm struggling at this stage.我认为这可以使用 for 循环轻松完成,但我在这个阶段很挣扎。 So please be kind and guide me.
所以请善待并指导我。
my hardcoded code is as follows:我的硬编码代码如下:
public override System.Collections.ObjectModel.ObservableCollection ExtractSamples() { ObservableCollection samples = new ObservableCollection();公共覆盖 System.Collections.ObjectModel.ObservableCollection ExtractSamples() { ObservableCollection samples = new ObservableCollection();
List<string> lines = this.GetTextLines();
foreach (string line in lines)
{
string[] parts = line.Replace("\"", "").Split(new string[] { "," }, StringSplitOptions.None);
for (int i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Trim();
}
Sample sample = new Sample(parts[1].Trim()); //for reading sample name Test1, Test2
samples.Add(sample);
sample.AddResult(DateTime.Now, "C1", parts[2]); //for adding Sample headers and it's Value like C1, 0.001692
sample.AddResult(DateTime.Now, "C2", parts[3]);
sample.AddResult(DateTime.Now, "C3", parts[4]);
}
return samples;
}
Here is how you do it by using a library called CsvHelper: https://joshclose.github.io/CsvHelper/以下是使用名为 CsvHelper 的库的方法: https://joshclose.github.io/CsvHelper/
The example is taken(modified a little) from the CsvHelper site and demonstrates a while loop:该示例取自 CsvHelper 站点(稍作修改)并演示了一个 while 循环:
void Main()
{
using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = new List<CsvData>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
var record = new CsvData
{
C1 = csv.GetField("C1"),
C2 = csv.GetField("C2"),
C3 = csv.GetField("C3")
};
records.Add(record);
}
}
}
public class CsvData
{
public string C1 { get; set; }
public string C2 { get; set; }
public string C3 { get; set; }
}
Let me know if there is anything unclear.让我知道是否有任何不清楚的地方。 Also it would be good if you posted what you have coded so far.
如果您发布到目前为止您已编码的内容,那将是一件好事。
Update related to comments与评论相关的更新
List<string> lines = this.GetTextLines();
var c1HeaderIndex = lines[0].FindIndex(x => x == "C1");
var c2HeaderIndex = lines[0].FindIndex(x => x == "C2");
var c3HeaderIndex = lines[0].FindIndex(x => x == "C3");
sample.AddResult(DateTime.Now, "C1", parts[c1HeaderIndex]);
sample.AddResult(DateTime.Now, "C2", parts[c2HeaderIndex]);
sample.AddResult(DateTime.Now, "C3", parts[c3HeaderIndex]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.