如何检查数组中没有重复项?

问题描述 投票:0回答:2

我正在用 C# 编写一个应用程序,提示用户输入 Automobile 类对象的数据。程序提示用户输入数据的类的属性之一是 ID 号。如果数据输入过程中任何 ID 号重复,程序必须重新提示用户。我怎样才能做到这一点?

这是该类的代码:

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

namespace AutomobileDemo
{
    internal class Automobile : IComparable
    {
        public int ID { get; set; }
        public string Make { get; set; }
        public int Year { get; set; }
        public double Price { get; set; }

        public override string ToString()
        {
            return ID + ": " + Make + " - " + Year + " - " + Price.ToString("C");
        }

        int IComparable.CompareTo(object obj)
        {
            Automobile anAutomible = (Automobile)obj;

            return this.ID.CompareTo(anAutomible.ID);
        }
    }
}

这是主类的代码:

namespace AutomobileDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Automobile[] cars = new Automobile[8];
            double totalPrices = 0;

            for (int i = 0; i < cars.Length; ++i)
            {
                cars[i] = new Automobile();

                Console.Write("ID number: ");
                cars[i].ID = Convert.ToInt32(Console.ReadLine());
                Console.Write("Make: ");
                cars[i].Make = Console.ReadLine() ?? "";
                Console.Write("Year: ");
                cars[i].Year = Convert.ToInt32(Console.ReadLine());
                Console.Write("Price: ");
                cars[i].Price = Convert.ToDouble(Console.ReadLine());
                totalPrices += cars[i].Price;

                Console.WriteLine();
            }

            Array.Sort(cars);

            for (int i = 0; i < cars.Length; ++i)
                Console.WriteLine(cars[i].ToString());

            Console.WriteLine("\nTotal of all prices: " + totalPrices.ToString("C"));
        }
    }
}
c# arrays class object unique
2个回答
0
投票

由于您询问基础知识,所以我假设您无法使用现有的数据结构或不熟悉函数,因此我将只提供应该有效的代码片段

int id;
bool isUnique;

do
{
Console.Write("ID number: ");
id = Convert.ToInt32(Console.ReadLine());
isUnique = true; // Assume the ID is unique initially

// Check the entered ID against all previously entered IDs
for (int j = 0; j < i; j++)
{
    if (cars[j].ID == id)
    {
        Console.WriteLine("This ID has already been entered. Please enter a unique ID.");
        isUnique = false; // Mark as not unique and break the loop
        break;
    }
}

if (isUnique)
{
    cars[i].ID = id; // Set the ID only if it is unique
}

} while (!isUnique); // Keep looping until a unique ID is entered

0
投票

您可以使用 Array.Exists 方法来检查数组是否已经包含匹配的元素。

var inputID = Convert.ToInt32(Console.ReadLine());

bool duplicateId = Array.Exists(cars , element => element.ID == inputID);
if (duplicateId) {
  // Handle duplication
}
else {
  cars[i].ID = inputID;
  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.