Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未能对包含对象的数组进行排序。C#_C#_Arrays_Sorting - Fatal编程技术网

未能对包含对象的数组进行排序。C#

未能对包含对象的数组进行排序。C#,c#,arrays,sorting,C#,Arrays,Sorting,我正在做一个学校的项目,我花了5个小时试图了解如何对包含四维对象的数组进行排序。我开始做的是按照productCode或drinkaname对它们进行排序。当我阅读分类线程时,人们告诉OP使用LINQ。我不应该用那个,我越来越不知道该用什么方法。老师告诉我,使用冒泡排序(我知道算法很糟糕),我在一个包含一维的数组上做得很好。我求助于尝试Array.Sort,但随后我得到了System.invalidooperationexception 我快发疯了,即使我读了多篇关于这个主题的文章,我还是被卡住

我正在做一个学校的项目,我花了5个小时试图了解如何对包含四维对象的数组进行排序。我开始做的是按照
productCode
drinkaname
对它们进行排序。当我阅读分类线程时,人们告诉OP使用LINQ。我不应该用那个,我越来越不知道该用什么方法。老师告诉我,使用冒泡排序(我知道算法很糟糕),我在一个包含一维的数组上做得很好。我求助于尝试
Array.Sort
,但随后我得到了
System.invalidooperationexception

我快发疯了,即使我读了多篇关于这个主题的文章,我还是被卡住了。我可能以错误的方式使用了
ToString
。任何轻推都将不胜感激

class soda
{
    string drinkName;   
    string drinkType;
    int drinkPrice;
    int productCode;

    //Construct for the beverage
    public soda(string _drinkName, string _drinkType, int _drinkPrice, int _productCode)
    {
        drinkName = _drinkName;
        drinkType = _drinkType;
        drinkPrice = _drinkPrice;
        productCode = _productCode;
    }

    //Property for the drink name e.g. Coca Cola, Ramlösa or Pripps lättöl
    public string Drink_name()
    {
        return drinkName;
        //set { drinkName = value; }
    }

    //Property for the drink type e.g. Soda, fizzy water or beer
    public string Drink_type()
    {
        return drinkType;
        //set { drinkType = value; }
    }

    //Property for the drink price in SEK
    public int Drink_price()
    {
        return drinkPrice;
        //set { drinkPrice = value; }
    }

    //Property for the product code e.g. 1, 2 or ...
    public int Product_code()
    {
        return productCode;
        //set { productCode = value; }
    }

    //Property for the product code e.g. 1, 2 or ...
    public int _Product_code
    {
        get { return productCode; }
        set { productCode = value; }
    }

    public override string ToString()
    {
        return string.Format(drinkName + " " + drinkType + " " + drinkPrice + " " + productCode);
        //return string.Format("The beverage {0} is of the type {1} and costs {2} SEK.", drinkName, drinkType, drinkPrice, productCode);
    }
}

class Sodacrate
{
    private soda[] bottles;         //Crate the array bottles from the class soda.
    private int antal_flaskor = 0;  //Keeps tracks on the amount of bottles. 25 is the maximum allowed.

    //Construct
    public Sodacrate()
    {
        bottles = new soda[25];
    }

    public void sort_sodas()
    {
        string drinkName = "";
        int drinkPrice = 0;
        int productCode = 0;
        Array.Sort(bottles, delegate (soda bottle1, soda bottle2) { return bottle1._Product_code.CompareTo(bottle2._Product_code); });
        foreach (var beverage in bottles)
        {
            if (beverage != null)
            {
                drinkName = beverage.Drink_name(); drinkPrice = beverage.Drink_price(); productCode = beverage.Product_code();
                Console.Write(drinkName + " " + drinkPrice + " " + productCode);
            }
        }
    }
}
----------------------编辑---------------
谢谢你的帮助,我正在接近我的解决方案,我不得不在周四吃午饭来解决我的问题

我仍然对我的同类有问题

//Exception error When I try to have .Product_Name the compiler protests. Invalid token
public void sort_Sodas()
{
    int max = bottles.Length;
    //Outer loop for complete [bottles]
    for (int i = 1; i < max; i++)
    {
        //Inner loop for row by row
        int nrLeft = max - i;
        for (int j = 0; j < (max - i); j++)
        {
            if (bottles[j].Product_code > bottles[j + 1].Product_code)
            {
                int temp = bottles[j].Product_code;
                bottles[j] = bottles[j + 1];
                bottles[j + 1].Product_code = temp;
            }
        }
    }
}
//尝试将.Product\u命名为编译器名称时出现异常错误。无效令牌
公共垃圾分类苏打水()
{
int max=瓶子长度;
//完整[瓶]的外环
对于(int i=1;i瓶[j+1]。产品代码)
{
int temp=瓶子[j]。产品代码;
瓶[j]=瓶[j+1];
瓶子[j+1]。产品代码=温度;
}
}
}
}
另外,当我希望所有这些值都对产品组为真时,我的线性搜索只返回一个值。为了更快地进行实验,我尝试了一些不同的方法。我将附加当前代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sodacrate
{
    //Soda - contains the properties for the bottles that go in to the crate
    class Soda : IComparable<Soda>
    {
        string drinkName;
        string drinkType;
        int drinkPrice;
        int productCode;

        //Construct for the beverage
        public Soda(string _drinkName, string _drinkType, int _drinkPrice, int _productCode)
        {
            drinkName = _drinkName;
            drinkType = _drinkType;
            drinkPrice = _drinkPrice;
            productCode = _productCode;
        }

        //Property for the drink name e.g. Coca Cola, Ramlösa or Pripps lättöl
        public string Drink_name
        {
            get { return drinkName; }
            set { drinkName = value; }
        }

        //Property for the drink type e.g. Soda, fizzy water or beer
        public string Drink_type
        {
            get { return drinkType; }
            set { drinkType = value; }
        }

        //Property for the drink price in SEK
        public int Drink_price
        {
            get { return drinkPrice; }
            set { drinkPrice = value; }
        }

        //Property for the product code e.g. 1, 2 or ...
        public int Product_code
        {
            get { return productCode; }
            set { productCode = value; }
        }

        //Override for ToString to get text instead of info about the object
        public override string ToString()
        {
            return string.Format("{0,0} Type {1,-16} Price {2,-10} Code {3, -5} ", drinkName, drinkType, drinkPrice, productCode);
        }

        //Compare to solve my issues with sorting
        public int CompareTo(Soda other)
        {
            if (ReferenceEquals(other, null))
                return 1;

            return drinkName.CompareTo(other.drinkName);
        }

    }

    static class Screen
    {
        // Screen - Generic methods for handling in- and output ======================================= >

        // Methods for screen handling in this object are:
        //
        //  cls()               Clear screen
        //  cup(row, col)       Positions the curser to a position on the console
        //  inKey()             Reads one pressed key (Returned value is : ConsoleKeyInfo)
        //  inStr()             Handles String
        //  inInt()             Handles Int
        //  inFloat()           Handles Float(Singel)
        //  meny()              Menu system , first invariable is Rubrik and 2 to 6 meny choises
        //  addSodaMenu()       The options for adding bottles

        // Clear Screen  ------------------------------------------
        static public void cls()
        {
            Console.Clear();
        }

        // Set Curser Position  ----------------------------------
        static public void cup(int column, int rad)
        {
            Console.SetCursorPosition(column, rad);
        }

        // Key Input --------------------------------------------
        static public ConsoleKeyInfo inKey()
        {
            ConsoleKeyInfo in_key; in_key = Console.ReadKey(); return in_key;
        }

        // String Input -----------------------------------------
        static public string inStr()
        {
            string in_string; in_string = Console.ReadLine(); return in_string;
        }

        // Int Input -------------------------------------------
        static public int inInt()
        {
            int int_in; try { int_in = Int32.Parse(Console.ReadLine()); }
            catch (FormatException) { Console.WriteLine("Input Error \b"); int_in = 0; }
            catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); int_in = 0; }
            return int_in;
        }

        // Float Input -------------------------------------------
        static public float inFloat()
        {
            float float_in; try { float_in = Convert.ToSingle(Console.ReadLine()); }
            catch (FormatException) { Console.WriteLine("Input Error \b"); float_in = 0; }
            catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); float_in = 0; }
            return float_in;
        }

        // Menu ------------------------------------------------
        static public int meny(string rubrik, string m_val1, string m_val2)
        {  // Meny med 2 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menSvar = menyInm();
            return menSvar;
        }

        static public int meny(string rubrik, string m_val1, string m_val2, string m_val3)
        {  // Meny med 3 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menSvar = menyInm();
            return menSvar;
        }

        static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4)
        {  // Meny med 4 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menSvar = menyInm();
            return menSvar;
        }

        static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5)
        {  // Meny med 5 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); menSvar = menyInm();
            return menSvar;
        }

        static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5, string m_val6)
        {  // Meny med 6 val ---------------------
            int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); ; menyRad(m_val6); menSvar = menyInm();
            return menSvar;
        }

        static void menyRubrik(string rubrik)
        {   // Meny rubrik --------
            cls(); Console.WriteLine("\n\t {0}\n----------------------------------------------------\n", rubrik);
        }

        static void menyRad(string menyVal)
        {   // Meny rad    --------
            Console.WriteLine("\t {0}", menyVal);
        }

        static int menyInm()
        { // Meny inmating ------
            int mVal; Console.Write("\n\t Menyval : "); mVal = inInt(); return mVal;
        }

        // Menu for adding bottles --------------------------------
        static public void addSodaMenu()
        {
            cls();
            Console.WriteLine("\tChoose a beverage please.");
            Console.WriteLine("\t1. Coca Cola");
            Console.WriteLine("\t2. Champis");
            Console.WriteLine("\t3. Grappo");
            Console.WriteLine("\t4. Pripps Blå lättöl");
            Console.WriteLine("\t5. Spendrups lättöl");
            Console.WriteLine("\t6. Ramlösa citron");
            Console.WriteLine("\t7. Vichy Nouveu");
            Console.WriteLine("\t9. Exit to main menu");
            Console.WriteLine("\t--------------------\n");
        }

        // Screen - Slut  <========================================
    } // screen <----

    class Sodacrate
    {
        // Sodacrate - Methods for handling arrays and lists of Soda-objects ======================================= >

        // Methods for Soda handling in this object are:
        //
        //  cls()               Clear screen
        //
        //

        private Soda[] bottles;                                         //Create they array where we store the up to 25 bottles
        private int antal_flaskor = 0;                                  //Keep track of the number of bottles in the crate

        //Inte Klart saknar flera träffar samt exception
        public int find_Soda(string drinkname)
        {
            //Betyg C
            //Beskrivs i läroboken på sidan 147 och framåt (kodexempel på sidan 149)
            //Man ska kunna söka efter ett namn
            //Man kan använda string-metoderna ToLower() eller ToUpper() 
            for (int i = 0; i < bottles.Length; i++)
            {
                if (bottles[i].Drink_name == drinkname)
                    return i;
            }
            return -1;
        }

        //Exception error
        public void sort_Sodas()
        {
            int max = bottles.Length;
            //Outer loop for complete [bottles]
            for (int i = 1; i < max; i++)
            {
                //Inner loop for row by row
                int nrLeft = max - i;
                for (int j = 0; j < (max - i); j++)
                {
                    if (bottles[j].Product_code > bottles[j + 1].Product_code)
                    {
                        int temp = bottles[j].Product_code;
                        bottles[j] = bottles[j + 1];
                        bottles[j + 1].Product_code = temp;
                    }
                }
            }
        }
/*
        //Exception error
        public void sort_Sodas_name()
        {
            int max = bottles.Length;
            //Outer loop for complete [bottles]
            for (int i = 1; i < max; i++)
            {
                //Inner loop for row by row
                int nrLeft = max - i;
                for (int j = 0; j < (max - i); j++)
                {
                    if (bottles[j].Drink_name > bottles[j + 1].Drink_name)
                    {
                        int temp = bottles[j].Drink_name;
                        bottles[j] = bottles[j + 1];
                        bottles[j + 1].Drink_name = temp;
                    }
                }
            }
        }
        */
        //Search for Product code
        public int LinearSearch(int key)
        {

            for (int i = 0; i < bottles.Length; i++)
            {
                if (bottles[i].Product_code == key)
                    return i;
            }
            return -1;
        }

        //Contains the menu to choose from the crates methods
        public void Run()
        {
            bottles[0] = new Soda("Coca Cola", "Soda", 5, 1);
            bottles[1] = new Soda("Champis", "Soda", 6, 1);
            bottles[2] = new Soda("Grappo", "Soda", 4, 1);
            bottles[3] = new Soda("Pripps Blå", "beer", 6, 2);
            bottles[4] = new Soda("Spendrups", "beer", 6, 2);
            bottles[5] = new Soda("Ramlösa", "water", 4, 3);
            bottles[6] = new Soda("Loka", "water", 4, 3);
            bottles[7] = new Soda("Coca Cola", "Soda", 5, 1);

            foreach (var beverage in bottles)
            {
                if (beverage != null)
                    Console.WriteLine(beverage);
            }
            Console.WriteLine("\n\tYou have {0} bottles in your crate:\n\n", bottleCount());

            Console.WriteLine("\nTotal value of the crate\n");
            int total = 0;
            for (int i = 0; i < bottleCount(); i++)
            {
                total = total + (bottles[i].Drink_price);
            }
            /*            int price = 0;                            //Causes exception error
                        foreach(var bottle in bottles)
                        {
                            price = price + bottle.Drink_price;
                        }
                        */
            Console.WriteLine("\tThe total value of the crate is {0} SEK.", total);
            //            Console.WriteLine("\tThe total value of the crate is {0} SEK.", price);

            Screen.inKey();
            Screen.cls();

            int test = 0;
            test = bottles[3].Product_code;
            Console.WriteLine("Product code {0} is in slot {1}", test, 3);
            Screen.inKey();

            Console.WriteLine("Type 1, 2 or 3");
            int prodcode = Screen.inInt();
            Console.WriteLine(LinearSearch(prodcode));

            Console.WriteLine("Product code {0} is in slot {1}", prodcode, (LinearSearch(prodcode)));
            Console.WriteLine(bottles[(LinearSearch(prodcode))]);
            Screen.inKey();
            //            sort_Sodas();                         //Causes Exception error I want it to sort on either product code or product name
            foreach (var beverage in bottles)
            {
                if (beverage != null)
                    Console.WriteLine(beverage);
            }
        }

        //Print the content of the crate to the console
        public void print_crate()
        {
            foreach (var beverage in bottles)
            {
                if (beverage != null)
                    Console.WriteLine(beverage);
                //else
                //Console.WriteLine("Empty slot");
            }
            Console.WriteLine("\n\tYou have {0} bottles in your crate:", bottleCount());
        }

        //Construct, sets the Sodacrate to hold 25 bottles
        public Sodacrate()
        {
            bottles = new Soda[25];
        }

        // Count the ammounts of bottles in crate
        public int bottleCount()
        {
            int cnt = antal_flaskor;
            // Loop though array to get not empty element
            foreach (var beverages in bottles)
            {
                if (beverages != null)
                {
                    cnt++;
                }
            }
            return cnt;
        }

        //Calculates the total value of the bottles in the crate
        public int calc_total()
        {
            int temp = 0;
            for (int i = 0; i < bottleCount(); i++)
            {
                temp = temp + (bottles[i].Drink_price);
            }
            return temp;
        }

        //Adds bottles in the crate.
        public void add_Soda()
        {
            /*Metod för att lägga till en läskflaska
            Om ni har information om både pris, läsktyp och namn
            kan det vara läge att presentera en meny här där man kan
            välja på förutbestämda läskflaskor. Då kan man också rätt enkelt
            göra ett val för att fylla läskbacken med slumpade flaskor
            */

            //I start of with adding 7 bottles to avoid having to add so many bottles testing functions. Remove block before release 
            bottles[0] = new Soda("Coca Cola", "Soda", 5, 1);
            bottles[1] = new Soda("Champis", "Soda", 6, 1);
            bottles[2] = new Soda("Grappo", "Soda", 4, 1);
            bottles[3] = new Soda("Pripps Blå", "lättöl", 6, 2);
            bottles[4] = new Soda("Spendrups", "lättöl", 6, 2);
            bottles[5] = new Soda("Ramlösa citron", "mineralvatten", 4, 3);
            bottles[6] = new Soda("Vichy Nouveu", "mineralvatten", 4, 3);
            //<======================================================================================================= End block

            int beverageIn = 0;                                                 //Creates the menu choice-variable
            while (beverageIn != 9)                                             //Exit this menu by typing 9 - This value should be different if we add more bottle types to add.
            {
                Screen.addSodaMenu();                                           //Calls the menu in the Screen-class
                Console.WriteLine("You have {0} bottles in the crate.\n\nChoose :", bottleCount());
                Screen.cup(8, 13);
                int i = bottleCount();                                          //Keeps track of how many bottles we have in the crate. If the crate is full we get expelled out of this method
                if (i == 25)
                { beverageIn = 9; }
                else beverageIn = Screen.inInt();                               //end

                switch (beverageIn)                                             //Loop for adding bottles to the crate exit by pressing 9
                {
                    case 1:
                        i = bottleCount();
                        bottles[i] = new Soda("Coca Cola", "Soda", 5, 1);
                        i++;
                        break;

                    case 2:
                        i = bottleCount();
                        bottles[i] = new Soda("Champis", "Soda", 6, 1);
                        i++;
                        break;

                    case 3:
                        i = bottleCount();
                        bottles[i] = new Soda("Grappo", "Soda", 4, 1);
                        i++;
                        break;

                    case 4:
                        i = bottleCount();
                        bottles[i] = new Soda("Pripps Blå lättöl", "lättöl", 6, 2);
                        i++;
                        break;

                    case 5:
                        i = bottleCount();
                        bottles[i] = new Soda("Spendrups lättöl", "lättöl", 6, 2);
                        i++;
                        break;

                    case 6:
                        i = bottleCount();
                        bottles[i] = new Soda("Ramlösa citron", "mineralvatten", 4, 3);
                        i++;
                        break;

                    case 7:
                        i = bottleCount();
                        bottles[i] = new Soda("Vichy Nouveu", "mineralvatten", 4, 3);
                        i++;
                        break;

                    case 9:
                        i = bottleCount();
                        if (i == 25)
                        {
                            Console.WriteLine("\tThe crate is full\n\tGoing back to main menu. Press a key: ");
                        }
                        Console.WriteLine("Going back to main menu. Press a key: ");
                        break;

                    default:                                                                    //Default will never kick in as I have error handling in Screen.inInt()
                        Console.WriteLine("Error, pick a number between 1 and 7 or 9 to end.");
                        break;
                }
            }
        }


        // Sodacrate - End  <========================================

        class Program
        {
            public static void Main(string[] args)
            {
                //Skapar ett objekt av klassen Sodacrate som heter Sodacrate
                var Sodacrate = new Sodacrate();
                Sodacrate.Run();
                Console.Write("Press any key to continue . . . ");
                Console.ReadKey(true);
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用系统线程;
使用System.Threading.Tasks;
名称空间碳酸钠
{
//苏打水-包含装入板条箱的瓶子的属性
类别:I可比
{
串饮器;
字符串类型;
int饮用米;
int产品代码;
//饮料的构造
公共苏打水(字符串饮用名称、字符串饮用类型、整数饮用价格、整数产品代码)
{
drinkaname=_drinkaname;
drinkType=_drinkType;
酒水价格=(U)酒水价格;
productCode=\u productCode;
}
//饮料名称的属性,例如可口可乐、Ramlösa或Pripps lättöl
公共字符串名称
{
获取{return drinkName;}
设置{drinkName=value;}
}
//饮料类型的属性,如苏打水、汽水或啤酒
公共字符串类型
{
获取{return drinkType;}
设置{drinkType=value;}
}
//以瑞典克朗计算的饮料价格
公共国际饮料价格
{
获取{return drinkPrice;}
设置{drinkPrice=value;}
}
//产品代码的属性,例如1、2或。。。
公共整数乘积_码
{
获取{return productCode;}
设置{productCode=value;}
}
//重写ToString以获取文本而不是有关对象的信息
公共重写字符串ToString()
{
返回字符串.Format(“{0,0}类型{1,-16}价格{2,-10}代码{3,-5}”,drinkName,drinkType,drinkPrice,productCode);
}
//用排序来解决我的问题
公共内部比较(其他)
{
if(ReferenceEquals(其他,空))
返回1;
返回drinkName.CompareTo(其他drinkName);
}
}
静态类屏幕
{
//屏幕-处理输入和输出的通用方法============================================>
//此对象中的屏幕处理方法有:
//
//cls()清除屏幕
//cup(行、列)将光标定位到控制台上的某个位置
//inKey()读取一个按下的键(返回值为:ConsoleKeyInfo)
//inStr()处理字符串
//Int()处理Int
//inFloat()句柄浮动(Single)
//菜单系统,第一个不变的是Rubrik和2到6个菜单选项
//addSodaMenu()添加瓶子的选项
//清屏------------------------------------------
静态公共void cls()
{
Console.Clear();
}
//设置光标位置----------------------------------
静态公共空杯(内柱,内弧度)
{
Console.SetCursorPosition(列,rad);
}
//关键输入--------------------------------------------
静态公共控制台eKeyInfo inKey()
{
ConsoleKeyInfo in_key;in_key=Console.ReadKey();返回in_key;
}
//字符串输入-----------------------------------------
静态公共字符串inStr()
{
字符串in_string;in_string=Console.ReadLine();返回in_string;
}
//整数输入-------------------------------------------
静态公共输入()
{
int-in;尝试{int-in=Int32.Parse(Console.ReadLine());}
catch(FormatException){Console.WriteLine(“输入错误\b”);int_in=0;}
catch(OverflowException){Console.WriteLine(“Input Owerflow\b”);int_in=0;}
返回int_in;
}
//浮点输入-------------------------------------------
静态公共浮动inFloat()
{
float float_in;尝试{float_in=Convert.ToSingle(Console.ReadLine());}
捕获(格式化异常){
public interface IComparable<T>
{
    int CompareTo(T other);
}
public class Soda: IComparable<Soda>
{
    ....
    public int CompareTo(Soda other)
    {
        if (ReferenceEquals(other, null))
           return 1;

        return drinkName.CompareTo(other.drinkName);
    }
}