簡體   English   中英

C#輸入的學生成績和姓名排序

[英]Sorting the grade and name of students inputting in C#

這是我的代碼:

我還想從多個名稱的數字輸入中獲取一個數字,並在排序結束時按輸出中輸入的數字的數字和名稱進行排序。

我不被允許使用類。

    int[] arr1 = new int[10];
    string[] name = new string[10];
    int n, i, j, tmp;


    Console.Write("\n\nSort elements of array in ascending order :\n");
    Console.Write("----------------------------------------------\n");

    Console.Write("Input the size of array : ");
    n = Convert.ToInt32(Console.ReadLine());

    Console.Write("Input {0} elements in the array :\n", n);
    for (i = 0; i < n; i++)
    {
        Console.WriteLine("Enter name {0}", i);
        name[i] = Console.ReadLine();
        Console.Write("element - {0} : ", i);
        arr1[i] = Convert.ToInt32(Console.ReadLine());
    }

    for (i = 0; i < n; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (arr1[j] < arr1[i])
            {
                tmp = arr1[i];
                arr1[i] = arr1[j];
                arr1[j] = tmp;


            }
        }
    }
    Console.Write("\nElements of array in sorted ascending order:\n");
    for (i = 0; i < n; i++)
    {
        Console.Write("{0}, {1}  ", arr1[i],name[i]);
    }
    Console.Write("\n\n");
    Console.ReadLine();

如果你可以使用列表類型,你可以試試這個代碼:

        List<dynamic> lst= new List<dynamic>();
        int n;


        Console.Write ( "\n\nSort elements of array in ascending order :\n" );
        Console.Write ( "----------------------------------------------\n" );

        Console.Write ( "Input the size of array : " );
        n = Convert.ToInt32 ( Console.ReadLine ( ) );

        Console.Write ( "Input {0} elements in the array :\n", n );
        for (var  i = 0; i < n; i++ )
        {
            Console.WriteLine ( "Enter name {0}", i );
            var name = Console.ReadLine ( );
            Console.Write ( "element - {0} : ", i );
            var elem = Convert.ToInt32 ( Console.ReadLine ( ) );
            lst.Add ( new { name = name, elem = elem } );
        }
        Console.Write ( "\nElements of array in sorted ascending order:\n" );

        lst.OrderBy ( t => t.elem ).ToList ( ).ForEach ( y => {
            Console.Write ( "{0}, {1}  ", y.elem, y.name );
        } );
        Console.Write ( "\n\n" );
        Console.ReadLine ( );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM