gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:28 25 4
gpt4 key购买 nike

如何在 wpf -xaml (C#) 中编写代码以读取 .csv 文件中的特定行。我制作的元素周期表上的每个按钮都会转到一个新窗口,该窗口在 ListView 中显示有关它的具体内容。但我的问题是如何做到这一点?

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

最佳答案

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

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 值。如果您更喜欢基于一个的索引,只需将 .Skip(lineIndex) 更改为 .Skip(lineIndex - 1)

关于c# - 如何在 WPF (xaml) 中读取 .csv 文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32843583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com