0

I have a my collection class of items with fields.

class Item
{
    string s1;
    string s2;
    string s3;
    string d1;
    string d2;
}

MyCollection looks like that:

    public class  MyCollection : ICollection<Item>, IEnumerable
{}

I need to distinct that list by 's1', 's2', 's3' but in return get list with all these fields (s1, s2, s3, d1, d2), without duplicated items. So in other words, In return I need a MyCollection<Item>, not List<anonymousType>

For now I have something like

var list = source.Select(k => new { k.s1, k.s2, k.s2 }).Distinct().ToList();

but it returns a list with only s1,s2,s3 fields.

Is there any way to do it?

  • Which `d1` and `d2` do you want when you have multiple values of them for a given `s1, s2, s3`? You can start with a `GroupBy` instead of a distinct, then you can `Select(x => new Item{s1=x.s1, ...}`, there are several options but you need to know what to select for `d1, d2` – oerkelens Nov 23 '17 at 07:20

1 Answers1

3

You can create a IEqualityComparer<> and use that.

class ItemComparer : IEqualityComparer<Item>
{
    public bool Equals(Item x, Item y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(x, null)) return false;
        if (ReferenceEquals(y, null)) return false;
        if (x.GetType() != y.GetType()) return false;

        return x.s1 == y.s1 && x.s2 == y.s2 && x.s3 == y.s3;
    }

    public int GetHashCode(Item obj)
    {
        var hashCode = obj.s1.GetHashCode();
        hashCode = (hashCode * 397) ^ obj.s2.GetHashCode();
        hashCode = (hashCode * 397) ^ obj.s3.GetHashCode();
        return hashCode;
    }
}

Then you can do this

var distinctList = list.Distinct(new ItemComparer()).ToList();
sQuir3l
  • 1,315
  • 7
  • 10