如何在WPF (xaml)中读取.csv文件中的特定行

本文关键字:文件 csv 读取 WPF xaml | 更新日期: 2023-09-27 18:15:08

如何在wpf -xaml (c#)中读取.csv文件中的特定行?我制作的元素周期表上的每个按钮都会进入一个新窗口,在列表视图中显示有关它的特定内容。但我的问题是怎么做呢?

public class Atomic
{
    public string Group { get; set; }
    public string Period { get; set; }
    public string Block { get; set; }
    public string Atomicnumber { get; set; }
    public string Stateat { get; set; }
    public string Electronconfiguration { get; set; }
    public string ChemspiderID { get; set; }
    public Atomic(string group, string period, string block, string atomicnumber, string stateat, string electronconfiguration, string chemspiderID)
    {
        Group = group;
        Period = period;
        Block= block;
        Atomicnumber = atomicnumber;
        Stateat = stateat;
        Electronconfiguration = electronconfiguration;
        ChemspiderID = chemspiderID;
    }
}
public IEnumerable<Atomic> ReadCSV(string fileName)
{
    // We change file extension here to make sure it's a .csv file.
    // TODO: Error checking.
    string[] lines = File.ReadAllLines(System.IO.Path.ChangeExtension(fileName, ".csv"));
    // lines.Select allows me to project each line as a Person. 
    // This will give me an IEnumerable<Person> back.
    return lines.Select(line =>
    {
        string[] data = line.Split(';');
        // We return a person with the data in order.
        return new Atomic(data[0], data[1], data[2], data[3], data[4], data[5], data[6]);
    });
}

如何在WPF (xaml)中读取.csv文件中的特定行

如果您想要读取特定行,您可以执行以下操作。

public Atomic ReadCSV(string fileName, int lineIndex)
{
    return File.ReadLines(System.IO.Path.ChangeExtension(fileName, ".csv"))
               .Skip(lineIndex)
               .Select(line => line.Split(';'))
               .Select(data => new Atomic(data[0], data[1], data[2], data[3], data[4], data[5], data[6]))
               .FirstOrDefault();
}

这将读取文件的第一个lineNumber + 1行,读取最后一行并从该行创建Atomic对象。如果没有足够的行,它将返回一个null值。如果您喜欢基于1的索引,只需将.Skip(lineIndex)更改为.Skip(lineIndex - 1)