C#:使用lambda按每个集合元素分组
我有一个C#:使用lambda按每个集合元素分组,c#,entity-framework,linq,lambda,grouping,C#,Entity Framework,Linq,Lambda,Grouping,我有一个组件的集合,这些集合有一个Pax的集合: public class Component { public IEnumerable<Pax> Paxes { get; set; } } public class Pax { public int Number { get; set; } public int Room { get; set; } } 当然,这些群体并不在意料之中。组件中重复的PAX没有相同的对象引用,因此我必须在组表达式中比较
组件的集合
,这些集合有一个Pax的集合
:
public class Component
{
public IEnumerable<Pax> Paxes { get; set; }
}
public class Pax
{
public int Number { get; set; }
public int Room { get; set; }
}
当然,这些群体并不在意料之中。组件中重复的PAX没有相同的对象引用,因此我必须在组表达式中比较它们的属性,这就是我遇到的问题。您必须为它实现一个
IEqualityComparer
:
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();
}
}
List components=new List();
var result=components.GroupBy(c=>c.Paxes,newpaxescomparer());
公共类乘客比较:IEqualityComparer
{
公共布尔等于(IEnumerable x,IEnumerable y)
{
抛出新的NotImplementedException();
}
public int GetHashCode(IEnumerable obj)
{
抛出新的NotImplementedException();
}
}
等于
,您可以检查集合是否相同Pax
类的Equals
和GetHashCode
GetHashcode
-因为如果哈希值不同,将不会调用equals-Kirill在下面的评论您可以使用此通用集合相等比较器
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);
}
}
公共类集合QualityComparer:IEqualityComparer
{
public int GetHashCode(IEnumerable obj)
{
未经检查
{
返回对象聚合(17,(当前,项)=>current*31+item.GetHashCode());
}
}
公共布尔等于(IEnumerable x,IEnumerable y)
{
返回x.x(y);
}
}
然后
var q = components.GroupBy(c => c.Paxes, new CollectionEqualityComparer<Pax>()));
var q=components.GroupBy(c=>c.Paxes,newcollectionqualitycomparer());
这当然需要Pax对象覆盖
Equals
和GetHashCode
正确实现GetHashCode方法是至关重要的,因为如果哈希值不同,将不会调用Equals。@KirillBestemyanov-将您的注释添加到了答案中-很好
var q = components.GroupBy(c => c.Paxes, new CollectionEqualityComparer<Pax>()));