Display data in ascending order of a text file in C#.

huangapple go评论64阅读模式
英文:

how to display data in ascending order of a text file c#

问题

我需要按照项目编号的升序对我的代码进行排序并显示。以下是示例代码:

string data = $"{itemNumber}|{itemName}|{itemPrice}";

using (StreamWriter writer = File.AppendText("items.txt"))
{
    writer.WriteLine(data);
}

public void DisplayItemList()
{
    using (StreamReader reader = new StreamReader("items.txt"))
    {
        Console.WriteLine("\n ---------------------------------");
        Console.WriteLine(" Item No.     Item Name      Price");
        Console.WriteLine(" ---------------------------------");

        List<string> itemLines = new List<string>();

        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            itemLines.Add(line);
        }

        itemLines.Sort(); // 对项目行进行排序

        foreach (string line in itemLines)
        {
            string[] fields = line.Split('|');
            Console.WriteLine(String.Format(" {0,-13}{1,-16}{2,0}", fields[0], fields[1], fields[2]));
        }

        Console.Write("\n");
    }
}

这里是我的示例代码。如你所见,我有:

1 - oslopaper | 34 - bond | 11 - art

我希望它变成:

1 - oslopaper, 11 - art, 最后是 34 - bond

因为我想按升序排列。

英文:

i need to sort and display my code by ascending order based off on the item number. Here's the sample code.

string data = $&quot;{itemNumber}|{itemName}|{itemPrice}&quot;;

using (StreamWriter writer = File.AppendText(&quot;items.txt&quot;))
{
    writer.WriteLine(data);
}

public void DisplayItemList()
{
    using (StreamReader reader = new StreamReader(&quot;items.txt&quot;))
    {
        Console.WriteLine(&quot;\n ---------------------------------&quot;);
        Console.WriteLine(&quot; Item No.     Item Name      Price&quot;);
        Console.WriteLine(&quot; ---------------------------------&quot;);

        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            string[] fields = line.Split(&#39;|&#39;);
            Console.WriteLine(String.Format(&quot; {0,-13}{1,-16}{2,0}&quot;, fields[0], fields[1], fields[2]));
        }

        Console.Write(&quot;\n&quot;);
    }
}

here's my sample code. as you can see i have

1 - oslopaper | 34 - bond | 11 - art

I needed it to be

1 - oslopaper, 11 - art, lastly, 34 - bond 

because I wanted it to be in ascending order.

答案1

得分: 2

建议使用 *Linq* 来查询文件(在这里可以添加排序 - `OrderBy`;表示 - `Select`;标题 - `Prepend`):

```csharp
using System.Linq;
using System.IO;

...

public void DisplayItemList() {
  var result = File
    .ReadLines("items.txt")
    .Where(line => !string.IsNullOrWhiteSpace(line)) // 为了更安全
    .Select(line => line.Split('|'))
    .OrderBy(fields => int.Parse(fields[0]))
    .Select(fields => $" {fields[0],-13}{fields[1],-16}{fields[2],0}")
    .Prepend(" --------------------------------- ")
    .Prepend(" Item No.     Item Name      Price ")
    .Prepend(" --------------------------------- ");

  Console.Write(string.Join(Environment.NewLine, result));
}

<details>
<summary>英文:</summary>

I suggest *querying* file with a help of *Linq* (here you can add ordering - `OrderBy`; representing - `Select`, headers - `Prepend`):

using System.Linq;
using System.IO;

...

public void DisplayItemList() {
var result = File
.ReadLines("items.txt")
.Where(line => !string.IsNullOrWhiteSpace(line)) // to be on the safer side
.Select(line => line.Split('|'))
.OrderBy(fields => int.Parse(fields[0]))
.Select(fields => $" {fields[0],-13}{fields[1],-16}{fields[2],0}")
.Prepend(" --------------------------------- ")
.Prepend(" Item No. Item Name Price ")
.Prepend(" --------------------------------- ");

Console.Write(string.Join(Environment.NewLine, result));
}


</details>



# 答案2
**得分**: 0

你可以使用LINQ在显示之前对项目进行排序。

```csharp
var lines = File.ReadAllLines("items.txt")
                .OrderBy(line => int.Parse(line.Split('|')[0]));
英文:

you can sort items before displaying them by LINQ

var lines = File.ReadAllLines(&quot;items.txt&quot;)
                .OrderBy(line =&gt; int.Parse(line.Split(&#39;|&#39;)[0]));

huangapple
  • 本文由 发表于 2023年2月18日 19:35:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定