从文件中读取数据并使用c#对数据进行排序

本文关键字:数据 排序 文件 读取 | 更新日期: 2023-09-27 18:15:05

我需要从文本文件中读取2D数组,并按升序对列进行排序。

我当前的实现是:

1)读取文件&根据空白分割值2)为3个数组列表分配3个列值

我尝试用Sort()方法排序每个数组列表。但无法得到所需的输出,它只能对正数值进行排序&

代码示例,

        ArrayList col1 = new ArrayList();
        ArrayList col2 = new ArrayList();
        ArrayList col3 = new ArrayList();
        using (StreamReader sr = new StreamReader(@"E:'ArrayCol1.txt"))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                string[] split = Regex.Split(line, "[ 't]");
                if (split.Count() == 3)
                {
                    col1.Add(Convert.ToInt32(split[0]));
                    col2.Add(Convert.ToInt32(split[1]));
                    col3.Add(Convert.ToInt32(split[2]));
                }
            }
        }
        col1.Sort();
        foreach (int s in col1)
            Console.WriteLine(s);

Textfile Data Array[4,3]:-

50 10 77

- 2 -1

-20 -600 -200

10 -70 1000

预期输出,

50 10 1000

10 -70 77

- 2 -1

-20 -600 -200

从文件中读取数据并使用c#对数据进行排序

你试过调试吗?

Sort()按升序排序。我必须用OrderByDescending()使它下降。

重写你的代码:

List<int> col1 = new List<int>();
    List<int> col2 = new List<int>();
    List<int> col3 = new List<int>();
    using (var reader = new StreamReader(@"C:'users'susingh'desktop'data.txt"))
    {
        string line;
        while (true)
        {
            line = reader.ReadLine();
            if (line==null)
            {
                break;
            }
            var numArray = line.Split(''t');
            col1.Add(Int32.Parse(numArray[0]));
            col2.Add(Int32.Parse(numArray[1]));
            col3.Add(Int32.Parse(numArray[2]));
        }
    }
    var Foo = col1.OrderByDescending(x=>x);
    foreach (var element in Foo)
    {
        Console.WriteLine (element);
    }
ArrayList col1 = new ArrayList();
ArrayList col2 = new ArrayList();
ArrayList col3 = new ArrayList();
using (StreamReader sr = new StreamReader(@"Sample.txt"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        string[] split = Regex.Split(line, @"'s+");
        if (split.Count() == 3)
        {
            col1.Add(Convert.ToInt32(split[0]));
            col2.Add(Convert.ToInt32(split[1]));
            col3.Add(Convert.ToInt32(split[2]));
        }
    }
}
// sort all columns
col1.Sort();
col2.Sort();
col3.Sort();
// output is largest to smallest so invert sort
for (int i = col1.Count -1 ; i >= 0; i--)
{
    Console.WriteLine(string.Format("{0}'t{1}'t{2}", col1[i], col2[i], col3[i]));
}