【问题标题】:how to read a specific line in .csv file in WPF (xaml)如何在 WPF (xaml) 中读取 .csv 文件中的特定行
【发布时间】:2015-12-26 21:51:21
【问题描述】:

如何在 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]);
    });
}

【问题讨论】:

    标签: c# wpf xaml csv


    【解决方案1】:

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

    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)

    【讨论】:

    • 感谢您的帮助。我的问题是:当我单击按钮 btnHydrogen_MouseUp 时,它必须读取 .csv 文件中的第一行。这也与下一步按钮 btnLithium_MouseUp 读取第二行有关。是否必须在每个按钮事件中添加特殊代码?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2015-09-06
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多