天天看點

關于List<T>集合中的差集

差集在幾何數學中的定義:一般地,記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"}

Except(IEnumerable<T>) 通過使用預設的相等比較器對值進行比較生成兩個序列的差集。 (由 Enumerable 定義。)

通過使用指定的 IEqualityComparer<T> 對值進行比較産生兩個序列的差集。

示例:

  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};