在.Net中进行集合运算(使用 Iesi.Collections.dll)

    技术2022-05-11  33

    由于.NET框架本身没有提供集合运算功能,在使用这方面的功能时,我们可以借助第三方的类库来实现。在NHibernate 框架中有个Iesi.Collection.dll,这个类库提供了集合运算功能,并且支持泛型。

    功能: 主要是取得2个集合里, 相同、相异、联集的部份。 例子: using  System; using  System.Data; using  System.Configuration; using  System.Web; using  System.Web.Security; using  System.Web.UI; using  System.Web.UI.WebControls; using  System.Web.UI.WebControls.WebParts; using  System.Web.UI.HtmlControls; using  Iesi.Collections.Generic; public   partial   class  _Default : System.Web.UI.Page {     protected   void  Page_Load( object  sender, EventArgs e)    {        ISet < string >  Girls  =   new  HashedSet < string > ();            Girls.Add( " Christine " );            Girls.Add( " Eva " );            Girls.Add( " Jean " );            Girls.Add( " Novia " );           Girls.Add( " Winnie " );               ISet < string >  PMs  =   new  HashedSet < string > ();            PMs.Add( " Eva " );            PMs.Add( " Novia " );            PMs.Add( " Vincent " );            PMs.Add( " Williams " );            PMs.Add( " Winnie " );               ISet < string >  GirlPMs  =  Girls.Intersect(PMs);                    Response.Write( " 是女生且是PM: <br /> " );             foreach  ( string  s  in  GirlPMs) {                Response.Write(s  +   " <br /> " );            }               Response.Write( " <br /> " );            ISet < string >  GirlNotPMs  =  Girls.Minus(PMs);            Response.Write( " 是女生且不是PM: <br /> " );             foreach  ( string  s  in  GirlNotPMs) {                Response.Write(s  +   " <br /> " );            }               Response.Write( " <br /> " );            ISet < string >  GirlOrPMs  =  Girls.Union(PMs);            Response.Write( " 是女生或是PM: <br /> " );             foreach  ( string  s  in  GirlOrPMs) {                Response.Write(s  +   " <br /> " );            }               Response.Write( " <br /> " );            ISet < string >  NotMatch  =  Girls.ExclusiveOr(PMs);            Response.Write( " 是女生但不是PM,或是PM但不是女生: <br /> " );             foreach  ( string  s  in  NotMatch) {                Response.Write(s  +   " <br /> " );            }       }}

    运行结果: 

    是女生且是PM: EvaNoviaWinnie是女生且不是PM: ChristineJean是女生或是PM: ChristineEvaJeanNoviaWinnieVincentWilliams是女生但不是PM,或是PM但不是女生: ChristineWilliamsJeanVincent 

     

    补充: 1. 如果顺序是重要的,那 HashedSet 可以改成 SortedSet 2. 如果用SortedSet, 集合里面的元素必需继承IComparable接口 3. 更详细的介绍可参考 Add Support for "Set" Collections to .NET  

    最新回复(0)