0

I have an object with many variables and i wanted a distinct function that would compare two variables(customerid,status) to consider the duplicates, i'm using the compare below for that, but I wish to choose the priority in how the distinct function will delete the duplicates.

There is string variable called "file" which will have the name of a file(all with the same extension), but 3 differents possible suffix before the extension ("","_0","TEXT").For example

"file_Name.txt"

"file_Name_0.txt"

"file_Name_TEXT.txt"

When there is a duplicate, I wish "file_Name.txt" will be given priority to remain. How can i do that?

class CustomerComparer : IEqualityComparer<Customer>
{

    public bool Equals(Customer x, Customer y)
    {
        if (Object.ReferenceEquals(x, y)) return true;

        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        return x.customerid == y.customerid && x.status == y.status;
    }

    public int GetHashCode(Customer aprov)
    {
        if (Object.ReferenceEquals(aprov, null)) return 0;

        int hashProductName = aprov.status == null ? 0 : aprov.status.GetHashCode();

        int hashProductCode = aprov.customerid.GetHashCode();

        return hashProductName ^ hashProductCode;
    }

}
Carlos Siestrup
  • 1,031
  • 2
  • 13
  • 33

1 Answers1

0

I think you can group your customers:

    var filteredCustomers = new List<Customer>();
    var separators = new string[] { "_", ".txt" };

    foreach (var customers in allCustomers.GroupBy(c => new { Id = c.customerid, Status = c.status }))
    {
        Customer uniqueCustomer = customers.FirstOrDefault(c =>
        {
            var lastPart = c.file.Split(separators, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
            if (lastPart != "TEXT" && lastPart != "0")
            {
                return true;
            }
            return false;
        });
        if (uniqueCustomer == null)
        {
            uniqueCustomer = customers.FirstOrDefault();
        }
        filteredCustomers.Add(uniqueCustomer);
    }

Also it's possible to change the logic of finding the primer customer(e.g. to use RegEx) and move it to your Customer class as a property or method.

Roman Koliada
  • 4,286
  • 2
  • 30
  • 59