我有两个类型为ICollection<MyType>
的集合,它们分别叫做c1
和c2
。我想找到那些在c2
中而不在c1
中的项集合,其中判断是否相等的方法是基于MyType
的Id
属性。
在C#(3.0)中,最快的实现方式是什么?
我有两个类型为ICollection<MyType>
的集合,它们分别叫做c1
和c2
。我想找到那些在c2
中而不在c1
中的项集合,其中判断是否相等的方法是基于MyType
的Id
属性。
在C#(3.0)中,最快的实现方式是什么?
使用Enumerable.Except
,并特别是接受IEqualityComparer<MyType>
的重载:
var complement = c2.Except(c1, new MyTypeEqualityComparer());
请注意,这将产生集合差异,因此中的重复项只会在结果IEnumerable<MyType>中出现一次。在这里,您需要实现类似于IEqualityComparer<MyType>
的内容。
class MyTypeEqualityComparer : IEqualityComparer<MyType> {
public bool Equals(MyType x, MyType y) {
return x.Id.Equals(y.Id);
}
public int GetHashCode(MyType obj) {
return obj.Id.GetHashCode();
}
}
如果使用C# 3.0 + Linq:
var complement = from i2 in c2
where c1.FirstOrDefault(i1 => i2.Id == i1.Id) == null
select i2;
循环遍历补集以获取项目。
public class MyTypeComparer : IEqualityComparer<MyType>
{
public MyTypeComparer()
{
}
#region IComparer<MyType> Members
public bool Equals(MyType x, MyType y)
{
return string.Equals(x.Id, y.Id);
}
public int GetHashCode(MyType obj)
{
return base.GetHashCode();
}
#endregion
}
然后,使用Linq:
c3 collection = new collection().add(c1);
c3.add(c2);
var items = c3.Distinct(new MyTypeComparer());
where !c1.Any(i1 => i2.Id == i1.Id)
更高效? 在这种情况下,您在 where 条件中不检索任何值,只是检查项目的存在性。请参见 DotNetFiddle。 - Matt