差集在几何数学中的定义:一般地,记A,B是两个集合,则所有属于A且不属于B的元素构成的集合,叫做集合A减集合B(或集合A与集合B之差),类似地,对于集合A、B,我们把集合{x∣x∈A,且x∉B}叫做A与B的差集,记作A-B(或A\B),即A-B={x|x∈A且x∉ B}(或A\B={x|x∈A且x ∉B},同理 B-A={x∣x∈B且x∉A} 叫做B与A的差集
通俗点讲就是A-B 是属于A的但不属于B的那部分集合;
在.NET中 List<T>.Except()来实现集合的差集;
如:
List<string> A=new List(){"A","B","C"} List<string> B=new List(){"C","D"}
var m= A.Except(B).ToList();
此时 m集合中的对象就是{"A","B"}
通过使用默认的相等比较器对值进行比较生成两个序列的差集。 (由 定义。) |
通过使用指定的 对值进行比较产生两个序列的差集。
示例:
public class PublishStock
{ public string EID { get; set; }//证券编码 public string SECURITYCODE { get; set; } //证券简称 public string SECURITYSHORTNAME { get; set; }
// 市场缩写
public string MARKETABR { get; set; }//市场编码
public string MARKETCODE { get; set; }}
public class PublishStockComparer : IEqualityComparer<PublishStock> {public bool Equals(PublishStock x, PublishStock y)
{ //Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) return true;//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false;//Check whether the products' properties are equal.
return x.SECURITYCODE == y.SECURITYCODE && x.MARKETCODE == y.MARKETCODE; }public int GetHashCode(PublishStock product)
{ //Check whether the object is null if (Object.ReferenceEquals(product, null)) return 0;//Get hash code for the Name field if it is not null.
int hashProductName = product.SECURITYCODE == null ? 0 : product.SECURITYCODE.GetHashCode();//Get hash code for the Code field.
int hashProductCode =product.MARKETCODE==null?0: product.MARKETCODE.GetHashCode()//Calculate the hash code for the product.
return hashProductName ^ hashProductCode; }注:当证券编码 ( SECURITYCODE)与 市场编码(MARKETCODE)相同时,表示对象相等;
调用:
PublishStock A=new PublishStock(){ EID="1",SECURITYCODE="001",SECURITYSHORTNAME="ZZ",MARKETCODE="100"}
PublishStock B=new PublishStock(){ EID="2",SECURITYCODE="002",SECURITYSHORTNAME="ZZ",MARKETCODE="300"}
PublishStock C=new PublishStock(){ EID="3",SECURITYCODE="001",SECURITYSHORTNAME="ZZ",MARKETCODE="100"}
List<PublishStock> Lst_A=new List<PublishStock>(){A,B};
List<PublishStock> Lst_B=new List<PublishStock>(){C};
var m=Lst_A.Except(Lst_B,new PublishStockComparer()).ToList();
此时 m集合中的元素为{B};