且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中对二进制文件中的记录进行排序?

更新时间:2023-11-08 22:28:16

您必须格式化具有固定长度和前导零的数字,以便它们可以按文本排序。



一种选择是使用 Int32.ToString方法(字符串)(系统) [ ^ ]:

 bw.Write(  ID: +  Int32  .Parse(textBox2.Text).ToString(   D11)); 



但是从我的角度来看,你的代码不会在文件中写入换行符,以便 File.ReadAllLines 将返回一个只有一个字符串的数组。或者我会错过什么?


比较字符串时,比较的工作方式是逐个查看每个字符,直到找到两个字符串中不相同的单个字符。然后,比较的整个结果将基于这两个字符之间的差异。

因此,当您对包含数值的字符串进行排序时,排序顺序为:

 1 
10
11
12
13
...
18
19
2
20
21
...



为了正确比较数值,您需要左键填充所有数字零,所以当你写文件时它们是相同的长度:

 00001 
00002
00003
...
00009
00010
00011
...

或者将字符串值解析为数字并使用文件中相关子字符串上的int.TryParse进行比较。


Iam trying to sort records after writing it to text file with binary writer but program only sort from 0 to 9 when i put the id=10 program consider it 1 and put it after 1
this the code where i write,save andsort

What I have tried:

private void button1_Click(object sender, EventArgs e)
{
    BinaryWriter bw = new BinaryWriter(File.Open(Class1.filename, FileMode.Open, FileAccess.Write));
    int length = (int)bw.BaseStream.Length;

    if (length == 0)
    {
        bw.Write("ID :" + int.Parse(textBox2.Text));
        textBox3.Text = textBox3.Text.PadRight(9);
        bw.Write("Name :" + textBox3.Text.Substring(0, 9));

        length += Class1.rec_size;
    }
    else
    {
        bw.BaseStream.Seek(length, SeekOrigin.Begin);
        bw.Write("ID :" + int.Parse(textBox2.Text));
        textBox3.Text = textBox3.Text.PadRight(9);
        bw.Write("Name :" + textBox3.Text.Substring(0, 9));
    }

    textBox2.Text = textBox3.Text  = "";
    MessageBox.Show("Data is saved Successfully");

    bw.Close();

    string inFile = Class1.filename;
    string outFile = Class1.filename;

    var contents=File.ReadAllLines(inFile);
    Array.Sort(contents);
    File.WriteAllLines(outFile, contents);
}

You have to format the numbers with a fixed length and leading zeroes so that they can be sorted as text.

One option is to use the Int32.ToString Method (String) (System)[^]:
bw.Write("ID :" + Int32.Parse(textBox2.Text).ToString("D11"));


But from my point of view your code does not write line feeds to the file so that File.ReadAllLines will return an array with only one string. Or do I miss something?


When you compare strings, the comparison works by looking at each character one-by-one until it finds a single character which is not the same in both strings. the entire result of the comparison is then based on the difference between these two characters.
So when you sort strings containing numeric values, the sort order is:
1
10
11
12
13
...
18
19
2
20
21
...


In order to compare numeric values correctly, you would either need to left-pad all the number with zeros so they are the same length when you write the file:

00001
00002
00003
...
00009
00010
00011
...

Or parse the string value to a number and compare those, using int.TryParse on the relevant substring from the file.