AWooster February 2016

Remove Duplicates from Class only if both strings are duplicates

I have a C# class that contains 2 strings, orderNumber and trackingNumber. I created a List of this class and put data into it. I need to remove any duplicate where the orderNumber and trackingNumber are both duplicates. Sometimes the class might contain a duplicate orderNumber but the trackingNumbers are different so I need to keep both.

Thanks, Andrew

Answers


Igor Ĺ evo February 2016

You could concatenate these strings and then select based on the concatenated string.

List<Item> list = new List<Item>();
Item[] result = list.GroupBy(x => new {x.trackingNumber, x.orderNumber}).Select(x => x.First()).ToArray();

This should work fairly well if you aren't dealing with billions of entries.


ArnesTwin February 2016

I think you can do it like this. I assume that Entity class contains OrderNumber and TrackingNumber properties. You can replace it with your original class name.

public class EntityList : List<Entity>
{

    public void Add(Entity entity)
    {

        if (this.Any(n => n.OrderNumber == entity.OrderNumber && n.TrackingNumber == entity.TrackingNumber))
            return;

        base.Add(entity);

    }

}

and the usage :

        var entity1 = new Entity
        {
            OrderNumber = "1",
            TrackingNumber = "100"
        };
        var entity2 = new Entity
        {
            OrderNumber = "2",
            TrackingNumber = "101"
        };
        var entity3 = new Entity
        {
            OrderNumber = "1",
            TrackingNumber = "100"
        };


        var list = new EntityList();

        list.Add(entity1);
        list.Add(entity1);
        list.Add(entity3);

        Console.WriteLine("Count : " + list.Count);


alex.b February 2016

Let's say for example this is your class:

private class Foo
{
    public readonly string trackingNumber;
    public readonly string orderNumber;

    public Foo(string trackingNumber, string orderNumber)
    {
        this.trackingNumber = trackingNumber;
        this.orderNumber = orderNumber;
    }
}

Getting unique items by trackingNumber and orderNumber can be achieved by leveraging Distinct method passing appropriate comparer:

    private class ByTrackingNumberAndOrderComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            return string.Equals(x.trackingNumber, y.trackingNumber)
                && string.Equals(x.orderNumber, y.orderNumber);
        }

        public int GetHashCode(Foo obj)
        {
            return (obj.trackingNumber == null ? 0 : obj.trackingNumber.GetHashCode())
                ^ 397 ^ (obj.orderNumber == null ? 0 : obj.orderNumber.GetHashCode());
        }
    }

Usage:

Foo[] foos = Generate(150000);
Foo[] distinct = foos.Distinct(new ByTrackingNumberAndOrderComparer()).ToArray();

Post Status

Asked in February 2016
Viewed 2,384 times
Voted 13
Answered 3 times

Search




Leave an answer