C #: using lambda for GroupBy for each item in the collection

I have a collection Component, and these collections have a collection Pax:

public class Component
{
    public IEnumerable<Pax> Paxes { get; set; }  
}

public class Pax
{
    public int Number { get; set; }  
    public int Room { get; set; }
}

I would like to group my collection Component(which is IEnumerable<Component>) in the list of passengers.

var groups = components.GroupBy(c => c.Paxes);

Of course, these groups are not expected. Duplicate Paxes in components do not have the same reference to objects, so I have to compare their properties in a group expression, and this is where I got stuck.

+4
source share
2 answers

You must implement IEqualityComparerfor it:

List<Component> components = new List<Component>();
var result = components.GroupBy(c => c.Paxes, new PaxesComparer());

public class PaxesComparer : IEqualityComparer<IEnumerable<Pax>>
{
    public bool Equals(IEnumerable<Pax> x, IEnumerable<Pax> y)
    {
        throw new NotImplementedException();
    }

    public int GetHashCode(IEnumerable<Pax> obj)
    {
        throw new NotImplementedException();
    }
}
  • Equals - , , .
  • , Equals GetHashCode Pax.
  • , , GetHashCode - , , -
+4

.

public class CollectionEqualityComparer<T> : IEqualityComparer<IEnumerable<T>>
{
    public int GetHashCode(IEnumerable<T> obj)
    {
        unchecked
        {
            return obj.Aggregate(17, (current, item) => current * 31 + item.GetHashCode());
        }
    }

    public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
    {
        return x.SequenceEqual(y);
    }
}

var q = components.GroupBy(c => c.Paxes, new CollectionEqualityComparer<Pax>()));

, , , Pax Equals GetHashCode.

+2

Source: https://habr.com/ru/post/1651071/


All Articles