如何更改表格中的数字顺序

时间:2012-01-02 15:50:50

标签: c#

我是学习如何制作10或20或25号码表的新手。我正在做10号码表。例如,我有4个数字表1,2,3,4,并希望在最后写它像4,3,2,1 - 有人可以告诉我该怎么做?

我的节目

    static void Main(string[] args)
    {
        int[] p = new int[10] { 2, 9, 13, 3, 50, -8, -30, 0, 1, 4 };
        int vsota = 0;
        float povprecje = 0;

        for (int i = 0; i < p.Length; i++)
        {
            Console.WriteLine("p [{0}] = {1,3}", i, p[i]);
            vsota += p[i];
        }
        povprecje = (float)vsota/p.Length;
        Console.WriteLine();
        Console.WriteLine("Vsota = {0}!", vsota);
        Console.WriteLine("Povprecje = {0}!", povprecje);
        Console.ReadKey(true);
    }

6 个答案:

答案 0 :(得分:3)

您可以使用Linq's OrderByOrderByDescending方法对集合进行排序。在您的示例中:

int[] p = new int[10] { 2, 9, 13, 3, 50, -8, -30, 0, 1, 4 };
p = p.OrderByDescending( x => x ).ToArray();

编辑:将表达式添加到OrderByDescending方法中。此外,Linq适用于3.5及更高版本的框架,需要引用System.Linq命名空间。

答案 1 :(得分:0)

如果您使用的是List,则可以使用:

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        List<int> table = new List<int>();

        table.Add(1);
        table.Add(2);
        table.Add(3);
        table.Add(4);

        foreach(int item in table)
        {
            Console.WriteLine(item);
        }

        table.Reverse();

        Console.WriteLine();
        foreach(int item in table)
        {
            Console.WriteLine(item);
        }
    }
}

答案 2 :(得分:0)

我认为你的意思是想要反转数组。所以如果你有这个数组:

int[] a = new int[] { 0, 1, 2, 3 };

您想要反转元素,使它们为{ 3, 2, 1, 0 }

关键是你要交换元素。例如,如果您要写:

// swap first and last elements
int temp = a[0];
a[0] = a[a.Length - 1];
a[a.Length - 1] = temp;

然后你的数组将是{ 3, 1, 2, 0 }

然后,想法是交换a[0]a[length-1]。然后交换a[1]a[length-2]等,直到您将每个项目与其对应项目交换为止。

您可以通过一个循环完成此操作。

顺便说一句,Reverse方法仅适用于List类型。对于数组,Reverse方法实际上是LINQ扩展方法,您需要创建一个新数组。例如:

int[] b = a.Reverse.ToArray();

答案 3 :(得分:0)

要对一维数组进行排序,可以调用Array.Sort()和/或Array.Reverse()方法。更新您的示例,您可以执行以下操作:

int[] p = new int[10] { 2, 9, 13, 3, 50, -8, -30, 0, 1, 4 };
int vsota = 0;
float povprecje = 0;

for (int i = 0; i < p.Length; i++)
{
    Console.WriteLine("p [{0}] = {1,3}", i, p[i]);
    vsota += p[i];
}
povprecje = (float)vsota/p.Length;
Console.WriteLine();
Console.WriteLine("Vsota = {0}!", vsota);
Console.WriteLine("Povprecje = {0}!", povprecje);
Console.ReadKey(true);

// Sort (low to high) the int[] by calling the Array.Sort() method
Array.Sort(p);
foreach(int i in p)
{
    Console.WriteLine(i);
}

// Sort (high to low) the int[] by calling the Array.Reverse() method
Array.Reverse(p);
foreach(int i in p)
{
    Console.WriteLine(i);
}

答案 4 :(得分:0)

要反转数组:

p = p.Reverse().ToArray();

答案 5 :(得分:0)

这是对@Metro Smurf的LINQ解决方案的更新:

int[] p = new int[10] { 2, 9, 13, 3, 50, -8, -30, 0, 1, 4 };
p = p.OrderByDescending(x => x).ToArray();
相关问题