简体   繁体   English

C#将堆栈转换为数组并对其进行排序

[英]C# converting a stack to an array and sorting it

I recently got into C# and I was trying to learn a bit about Stacks. 我最近接触了C#,并试图学习一些有关Stacks的知识。 I wanted to try and sort a stack, by first converting it to an array but I got a weird error. 我想尝试通过首先将其转换为数组来对堆栈进行排序,但出现了一个奇怪的错误。

Here is my code: 这是我的代码:

using System;
using System.Collections.Generic;

class Program
{
    public static Stack<int> numbers = new Stack<int>();
    static void Main(string[] args)
    {
        string[] input = Console.ReadLine().Split(' ');

        int n = int.Parse(input[0]);
        int s = int.Parse(input[1]);
        int x = int.Parse(input[2]);

        input = Console.ReadLine().Split(' ');
        for (int i = 0; i < n; i++)
        {
            numbers.Push(int.Parse(input[i]));
        }

        for (int i = 0; i < s; i++)
        {
            numbers.Pop();
        }

        if (numbers.Count == 0)
            Console.WriteLine(0);
        else if (numbers.Contains(x))
            Console.WriteLine("true");
        else
            Console.WriteLine(Array.Sort(numbers.ToArray()));


    }
}

My issue is on the last else part of my code (last line) : 我的问题在代码的最后其他部分(最后一行):

Argument 1: cannot convert from 'void' to 'bool' 论点1:无法从'void'转换为'bool'

I was wondering why this is happening, when Array.Sort() , requires an Array as a parameter, and I pass number.ToArray() , which should return a new Array out of the numbers Stack. 我想知道为什么会发生这种情况,当Array.Sort()要求将Array作为参数时,我传递了number.ToArray() ,它应该从数字 Stack中返回一个新的Array。

Error appears due the fact Array.Sort returns void and not the expected array . 由于Array.Sort返回void而不是预期的数组 ,因此出现错误。

Additionally , Console.WriteLine gets inputs and prints it to Console, it can not get array and print that array, it will only print you the actual array address. 另外 ,Console.WriteLine获取输入并将其打印到Console,它无法获取数组并打印该数组,它只会打印您实际的数组地址。

In order to print array(or any collection) you should use string.Join which takes a collection and returns a string separated by delimiter. 为了打印数组(或任何集合),您应该使用string.Join ,它接受一个集合并返回由定界符分隔的字符串。

Pretty straightforward using System.Linq.OrderBy 使用System.Linq.OrderBy非常简单

numbers.OrderBy(num => num).ToArray();

Example: 例:

public static void Main()
{
    var numbers = new Stack<int>();
    numbers.Push(4);
    numbers.Push(1);
    numbers.Push(2);

    var numbersSorted = numbers.OrderBy(num => num).ToArray();
    Console.WriteLine(string.Join(", ", numbersSorted));
}

Output: 1, 2, 4 输出: 1,2,4

DotNetFiddle 点网提琴

Array.Sort carries out an in-place sort on the array. Array.Sort在数组上执行就地排序。 It does not return a new sorted array. 它不返回新的排序数组。 It is therefore a Void function. 因此,它是一个虚函数。

Modify your code; 修改您的代码;

int[] numberArray = numbers.ToArray();
numberArray.Sort();
Console.WriteLine(numberArray);

Array.Sort is a void method, you've to separate Sort and writing (to console) in two different statements. Array.Sort是一个void方法,您必须在两个不同的语句中将SortArray.Sort (控制台)分开。

I would suggest using OrderBy linq extension and string.Join together to have one liner display. 我建议使用OrderBy linq扩展名和string.Join一起显示一个衬板。

Console.WriteLine(string.Join(",", numbers.OrderBy(x=>x));

The error message is quite clear. 错误消息很清楚。 In this line: 在这一行:

Console.WriteLine(Array.Sort(numbers.ToArray()));

The Array.Sort doesn't return anything (void) but you're passing to Console.WriteLine which expects a parameter. Array.Sort不返回任何值(无效),但是您将传递给需要参数的Console.WriteLine

You should replace the last else with this: 您应该用这个替换最后一个:

var numbersArray = numbers.ToArray();
Array.Sort(numbersArray);

Console.WriteLine(string.Join(",", numbers));

You need to assign an array variable before sorting, which you can then writeline. 您需要在排序之前分配一个数组变量,然后可以写行。

    else
    {
        var array = numbers.ToArray();
        Array.Sort(array);
        Console.WriteLine(array);

    }

First convert as Array Object. 首先转换为Array对象。 then sort your array and then you should use 然后对数组进行排序,然后应该使用

Console.WriteLine(array) to print your Array. Console.WriteLine(array)以打印您的Array。

int[] numberArray = numbers.ToArray(); //change to Array.
  numberArray.sort();                   // it will sort your Array.
  Console.WriteLine(numberArray);   //display the sorted Array.

instead of 代替

 Console.WriteLine(Array.Sort(numbers.ToArray())); // here whatever Sort() method return will be printed as Output but infact Sort() returns void.

So Compile time your get Error: cannot convert from 'void' to 'bool' 因此,编译时您的get Error: cannot convert from 'void' to 'bool'

Thank you to everyone for the responses. 谢谢大家的答复。 I am coming from Java, where you could directly print a collection, that's why I tried to do it like that. 我来自Java,您可以在这里直接打印一个集合,这就是为什么我试图那样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM