C# HashSet<T> 简单使用

一个简单的HashSet<T> 的例子,介绍其简单的方法,深入学习可参考微软:https://msdn.microsoft.com/en-us/library/bb359438(v=vs.110).aspx

static void Main(string[] args)
        {   
            //定义两个哈希集合以及其中一个集合的子集
            HashSet<int> hashSet1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
            HashSet<int> hashSet2 = new HashSet<int>() { 6, 7, 8, 9, 10 };
            HashSet<int> hashSet1Sub = new HashSet<int>() { 4, 5 };
            HashSet<int> hashSetAll = new HashSet<int>();

            string message = String.Empty;
            bool result = false;

            #region Hash集合元素唯一性体现
            result = hashSet1.Add(1);    //集合1中添加重复元素
            if (result)
            {
                message = "Hash集合已存在该元素";
            }
            else
            {
                message = "元素添加成功";               
            }
            Console.WriteLine(message);
            #endregion

            #region Hash表子集、交集判断
            result = hashSet1.IsSubsetOf(hashSet2);
            if (result)
            {
                message = "Hash集合2是集合1的子集";
            }
            else
            {
                message = "Hash集合2不是集合1的自己";
            }
            Console.WriteLine(message);

            result = hashSet1.Overlaps(hashSet2);
            if (result)
            {
                message = "Hash集合1和Hash集合2存在交集";
            }
            else
            {
                message = "Hash集合1和hash集合2不存在交集";
            }

            result = hashSet1.IsSupersetOf(hashSet2);
            if (result)
            {
                message = "集合1完全包含集合2";
            }
            else
            {
                message = "集合1不完全包含集合2";
            }
            #endregion

            #region 集合的初始化
            hashSetAll = new HashSet<int>(hashSet1);
            hashSetAll.UnionWith(hashSet2);
            hashSetAll.UnionWith(hashSet1Sub);

            message = "输出所有集合的元素";
            Console.WriteLine(message);
            foreach (int item in hashSetAll)
            {
                Console.WriteLine(item);
            }
            #endregion

            #region 排除元素
            hashSetAll.ExceptWith(hashSet2);
            message = "排除了集合2并输出";
            Console.WriteLine(message);
            foreach (var item in hashSetAll)
            {
                Console.WriteLine(item);
            }
            #endregion

            Console.ReadKey();
        }

 

转载于:https://www.cnblogs.com/mahuanpeng/p/6337628.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值