Bruno
Bruno

Reputation: 4665

Group by a collection as the key

I have this kind of class :

public class EntityIdentifier
{
    int Id { get; set; }
    int EntityId { get; set; }
    int SourceId { get; set; }

    ICollection<BaseEntityIdentifierDetail> IdentifierValues { get; set; }
}

An EntityIdentifier consists of a list of keyvalue pairs (the IdentifierValues).

I then have a list of EntityIdentifier that I would like to group by the IdentifierValues property.

var allIds = myIdentifiers.GroupBy(i => i.IdentifierValues);

It compiles, but I am not sure how it will behave. My guess is I have to implement some overrides (like Equal and GetHashCode maybe) somewhere so that a list of objects can correctly be used as a grouping key.

Anyone know what to implement in order for a collection to be correctly used as a grouping key?

EDIT 1: For two EntityIdentifiers to be equal, their key-value pairs (IdentifierValues) must all be identical. E.g. all the same keys associated with same values and the lists of the same size.

EDIT 2: Code for the IdentifierValues:

public class BaseEntityIdentifierDetail
{
    public int Id { get; set; }
    public string Key { get; set; }
    public string Value { get; set; }
}

Upvotes: 2

Views: 511

Answers (1)

Erik Philips
Erik Philips

Reputation: 54676

You should probably implement the IEqualityComparer<T> interface. Then use the GroupBy() method that uses the IEqualityComparer<T> class defined.

public class ColectionBaseEntityIdentifierDetailComparer 
  : IEqualityComparer<ICollection<BaseEntityIdentifierDetail>>
{
    public bool Equals(ICollection<BaseEntityIdentifierDetail> left,
      ICollection<BaseEntityIdentifierDetail> right)
    {
        // compare left and right
        return true;
    }

    public int GetHashCode(ICollection<BaseEntityIdentifierDetail> obj)
    {
        // return correctly implemented GetHashCode()
        return 1; 
    }
}

Usage:

    var a = new List<EntityIdentifier>();

    var b = a.GroupBy(ei => ei.IdentifierValues, 
      new ColectionBaseEntityIdentifierDetailComparer());

Upvotes: 1

Related Questions