如何写入文本文件按年份排序

时间:2019-05-10 15:36:12

标签: c#

我无法按nobel [i] .year订购txt文件。 文件正在减少。我必须在成长中做。 我根本不是天才,所以请尽可能简单。

非常感谢。

struct datas
{
    public int year;
    public string type;
    public string firstname;
    public string lastname;
}
datas[] nobel= new datas[923];

using (var sw = new StreamWriter("orvosi.txt"))
{
    for (int i = 0; i < nobel.Length; i++)
    {
        if (nobel[i].type== "orvosi")
        {
            sw.WriteLine(nobeldij[i].year+ ": " +nobel[i].firstname+" "+nobel[i].lastname);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

在您的using语句之前:

nobel = nobel.OrderBy(x => x.year).ToArray();

答案 1 :(得分:1)

根据以后是否需要排序的数组,还可以将其简化为以下内容。还要注意字符串插值$docs),它简化了输出字符串的构造。

for (datas n in nobel.OrderBy(x=> x.year)) {
    if (n.type == "orvosi")
        sw.WriteLine($"{n.year}:{n.firstname} {n.lastname}");
}

答案 2 :(得分:0)

使用System.IO.File类和某些System.Linq.Enumerable扩展方法(WhereOrderBySelect),您可以将代码缩短为一条语句。

  • 我们可以使用File.WriteAllLines,它将IEnumerable的内容写入文件(每个项目都在其单独的行中)。

  • 我们首先可以使用type == "orvosi"子句将数据过滤到Where()的那些地方。

  • 然后,我们可以使用year通过OrderBy(data => data.year)属性对过滤的项目进行排序。

  • 最后,对于过滤后的有序集合中的每个项目,我们可以Select使用包含要写入文件的属性的字符串(使用string interpolation)。

例如:

File.WriteAllLines("orvosi.txt", nobel
    .Where(data => data.type == "orvosi")
    .OrderBy(data => data.year)
    .Select(data => $"{data.year}: {data.firstname} {data.lastname}"));