Я думаю, это то, что вы ищете:
public sealed class Order : IEquatable<Order>
{
// Properties & Fields
public int OrderNum { get; set; }
public string CustomerName { get; set; }
public double Quantity { get; set; }
public double ItemPrice { get; set; }
public double TotalPrice => Quantity*ItemPrice;
// Constructor
public Order(int orderNum, string customerName, double quantity, double itemPrice = 12.35)
{
this.OrderNum = orderNum;
this.CustomerName = customerName;
this.Quantity = quantity;
this.ItemPrice = itemPrice;
}
// Equality
/// <summary>
/// Equality overrides from <see cref="System.Object"/>
/// </summary>
/// <param name="obj">The object to compare this with</param>
/// <returns>False if object is a different type, otherwise it calls <code>Equals(Order)</code></returns>
public override bool Equals(object obj)
{
if (obj is Order order)
{
// Uses pattern matching when `obj` is of type `Order`
return Equals(order);
}
return false;
}
/// <summary>
/// Checks for equality among <see cref="Order"/> classes
/// </summary>
/// <param name="other">The other <see cref="Order"/> to compare it to</param>
/// <returns>True if equal</returns>
public bool Equals(Order other)
{
return OrderNum.Equals(other?.OrderNum);
}
/// <summary>
/// Calculates the hash code for the <see cref="Order"/>
/// </summary>
/// <returns>The int hash value</returns>
public override int GetHashCode()
{
return (17+23*OrderNum.GetHashCode());
}
// Display
public override string ToString()
{
return string.Join(Environment.NewLine, new string[] {
$"Order Number : {OrderNum}",
$"Customer name : {CustomerName}",
$"Item Price : {ItemPrice:F2}",
$"Quantity Ordered : {Quantity:F3}",
$"Total Price : {TotalPrice:F2}",
Environment.NewLine,
});
}
}
для использования следующим образом:
class Program
{
static void Main(string[] args)
{
// creating the orders
List<Order> orders = new List<Order>();
orders.Add(new Order(1, "Joe Bob", 2));
orders.Add(new Order(3, "Sally Bob", 4));
orders.Add(new Order(1, "Jimmy Bob", 5));
Console.WriteLine("List of all orders.");
foreach (var order in orders)
{
Console.WriteLine(order);
}
Console.WriteLine("Found the following duplicates.");
// Code taken from: https://stackoverflow.com/a/18547390/380384
// It uses the `IEquatable<>` interface to check for duplicates.
foreach (var item in orders.GroupBy((order) => order).Where(grp => grp.Count()>1))
{
Console.WriteLine(item.Key);
}
}
}
с выводом
List of all orders.
Order Number : 1
Customer name : Joe Bob
Item Price : 12.35
Quantity Ordered : 2.000
Total Price : 24.70
Order Number : 3
Customer name : Sally Bob
Item Price : 12.35
Quantity Ordered : 4.000
Total Price : 49.40
Order Number : 1
Customer name : Jimmy Bob
Item Price : 12.35
Quantity Ordered : 5.000
Total Price : 61.75
Found the following duplicates.
Order Number : 1
Customer name : Joe Bob
Item Price : 12.35
Quantity Ordered : 2.000
Total Price : 24.70