检查数组是否有重复的对象 - Equals()或Method?

时间:2014-04-19 19:55:49

标签: c# arrays methods equals

我正在自己学习C#并且坚持练习。我需要确保没有重复的OrderNumbers输入到我的订单数组中。我认为练习的想法是使用Equals()然而,我无法弄清楚如何让它工作。我还没有学到任何太过花哨的东西。 Equals()会比使用方法更好吗?此外,我不知道如何调用该方法,所以我看到了真值或假值。如果找到重复,则应循环并要求用户重新输入。因为我真的很沮丧,所以提前感谢你...我需要一位导师!

class Program
{
    static void Main()
    {
        Order[] order = new Order[3];
        int orderNumber;  // hold temp value until object is created
        string customerName;
        int qtyOrdered;

        for (int x = 0; x < order.Length; ++x) //to fill array
        {
            Console.Write("Enter Order Number: ");
            int.TryParse(Console.ReadLine(), out orderNumber); // put order number in temp

            if (order[x] != null) 
            {
                if (IsOrderNumberInUse(orderNumber, order) == true)
                {
                    Console.WriteLine("Duplicate order number");
                }
            }
                GetData(out customerName, out qtyOrdered);
                order[x] = new Order(orderNumber, customerName, qtyOrdered);

        }
        Console.ReadLine();
    }

   //METHOD TO CHECK FOR DUPLICATES
    private static bool IsOrderNumberInUse(int orderNumber, Order[] orders)
    {
        foreach (Order order in orders)
        {
            if (order.OrderNumber == orderNumber)
            {
                return true;
            }
        }
        // If orderNumber was not found
        return false;
    }

    static void GetData(out string customerName, out int qtyOrdered)
    {
        //Console.Write("Enter Order Number: ");
        //int.TryParse(Console.ReadLine(), out orderNumber);
        Console.Write("Enter Customer Name: ");
        customerName = Console.ReadLine();
        Console.Write("Enter Quantity Ordered: ");
        int.TryParse(Console.ReadLine(), out qtyOrdered);
    }

    class Order
    {
        private const double PRICE = 19.95;
        public int OrderNumber { get; set; }
        public string CustomerName { get; set; }
        public int QtyOrdered { get; set; }

        public double totalPrice
        {
            get
            {
                return QtyOrdered * PRICE;
            }
        }

        public Order(int orderNumber, string customer, int qty)  // Constructor
        {
            OrderNumber = orderNumber;
            CustomerName = customer;
            QtyOrdered = qty;
        }

        public override string ToString()
        {
            return ("\n" + GetType() + "\nCustomer: " + CustomerName + "\nOrder Number: " + OrderNumber +
                "\nQuantity:  " + QtyOrdered + "\nTotal Order:  " + totalPrice.ToString("C2"));
        }

        public override bool Equals(object x)
        {
            bool isEqual;

            if (this.GetType() != x.GetType())
                isEqual = false;
            else
            {
                Order temp = (Order)x;
                if (OrderNumber == temp.OrderNumber)
                    isEqual = true;
                else
                    isEqual = false;
            }
            return isEqual;
        }

        public override int GetHashCode()
        {
            return OrderNumber;
        }
    }
}

我正在尝试不使用列表,因为我已经学会了它,而我接下来的两个练习与此相关。我担心如果使用列表,我会更加迷失。我得到null错误,需要帮助修复它们。这是我的代码。使用Equals会比我目前正在努力的方法更好吗?感谢您的耐心......

    class Program
{
    static void Main()
    {
        Order [] orders  = new Order [3];
        int tempOrderNumber;
        string tempCustomerName;
        int tempQtyOrdered;

        for (int x = 0; x < orders.Length; ++x)  // fill list
        {
            tempOrderNumber = AskForOrderNumber(orders);
            GetData(out tempCustomerName, out tempQtyOrdered);
            orders[x] = new Order(tempOrderNumber, tempCustomerName, tempQtyOrdered);
        }
        Console.ReadLine();
    }

    private static int AskForOrderNumber(Order [] orders)
    {
        int tempOrderNumber;
        Console.Write("Enter Order Number: ");
        int.TryParse(Console.ReadLine(), out tempOrderNumber);

            if (orders[0] !=null && IsOrderNumberInUse(tempOrderNumber, orders) == true) //Check for duplicates
            {
                Console.WriteLine("Duplicate order number");
                AskForOrderNumber(orders);
            }
            return tempOrderNumber;
    }

    static void GetData(out string tempCustomerName, out int tempQtyOrdered)
    {
        Console.Write("Enter Customer Name: ");
        tempCustomerName = Console.ReadLine();
        Console.Write("Enter Quantity Ordered: ");
        int.TryParse(Console.ReadLine(), out tempQtyOrdered);
    }

    private static bool IsOrderNumberInUse(int tempOrderNumber, Order[] orders)
    {
        foreach (Order order in orders)
            {
            if (order.OrderNumber == tempOrderNumber)
                {
                    return true;
                }
            }
            return false;
    }

    class Order
    {
        private const double PRICE = 19.95;
        public int OrderNumber { get; set; }
        public string CustomerName { get; set; }
        public int QtyOrdered { get; set; }

        public double totalPrice
        {
            get
            {
                return QtyOrdered * PRICE;
            }
        }

        public override string ToString()
        {
            return ("\n" + GetType() + "\nCustomer:  " + CustomerName + "\nOrder Number:  " + OrderNumber +
                "\nQuantity:  " + QtyOrdered + "\nTotal Order:  " + totalPrice.ToString("C2"));
        }

        public Order(int orderNumber, string customerName, int qtyOrdered)
        {
            OrderNumber = orderNumber;
            CustomerName = customerName;
            QtyOrdered = qtyOrdered;
        }

        public override bool Equals(Object x)
        {
            bool isEqual;

            if(this.GetType() != x.GetType())
                isEqual = false;
            else
            {
                Order temp = (Order) x;
                if(OrderNumber == temp.OrderNumber)
                    isEqual = true;
                else
                    isEqual = false;
            }
            return isEqual;
        }
        public override int GetHashCode()
        {
            return OrderNumber;
        }   
    }
}

1 个答案:

答案 0 :(得分:1)

为了解决您的问题,我建议您使用List<Order>,因为列表可以调整大小我相信它们将是更好的选择。

您当前的方法不起作用,因为您在 之后才创建order[x]

使用列表/固定代码

你应该使用临时orderNumber,但是因为数组是空的,你也可以在第一次检查时得到空错误(可以修复),因此我会再次推荐一个List

List<Order> orders = new List<Order>(); //Orders list
int orderNumber; //Temporary order number
string customerName; //Temporary customer name 
int qtyOrdered; //Temporary quantity

for (int x = 0; x < 3; ++x) //Fill List
{
    Console.Write("Enter Order Number: ");
    int.TryParse(Console.ReadLine(), out orderNumber); //Parse order number

    if (IsOrderNumberInUse(orderNumber, orders) == true) //Check for duplicates
    {
        Console.WriteLine("Duplicate order number");
    }

    //Get data and add to list
    GetData(out customerName, out qtyOrdered);
    orders.Add(new Order(orderNumber, customerName, qtyOrdered));

}
Console.ReadLine();

如果输入无效,则再次询问用户

上面的示例显示了我修复问题并使用List的建议,但是如果您想进一步提示用户重新输入它的值正在使用中。您可以通过创建一个方法来询问用户输入,并通过递归,再次询问它们是否正在使用。

...
for (int x = 0; x < 3; ++x) //Fill List
{
    orderNumber = AskForOrderNumber(orders);

    //Get data and add to list
    GetData(out customerName, out qtyOrdered);
    orders.Add(new Order(orderNumber, customerName, qtyOrdered));

    }
    Console.ReadLine();
}

private static int AskForOrderNumber(List<Order> orders)
{
    int orderNumber;
    Console.Write("Enter Order Number: ");
    int.TryParse(Console.ReadLine(), out orderNumber); //Parse order number
    if (IsOrderNumberInUse(orderNumber, orders) == true) //Check for duplicates
    {
        Console.WriteLine("Duplicate order number");
        AskForOrderNumber(orders);
    }
    return orderNumber;
}

检查验证的更好方法

您当前检查重复项的方法也没有任何问题,但可以使用LINQ进行改进。 (using System.LINQ

private static bool IsOrderNumberInUse(int orderNumber, List<Order> orders)
{
     return orders.Any(o => o.OrderNumber == orderNumber);
}