zoukankan      html  css  js  c++  java
  • C#集合之集(set)

      包含不重复元素的集合称为“集(set)”。.NET Framework包含两个集HashSet<T>和SortedSet<T>,它们都实现ISet<T>接口。HashSet<T>集包含不重复元素的无序列表,SortedSet<T>集包含不重复元素的有序列表。
      ISet<T>接口提供的方法可以创建合集,交集,或者给出一个是另一个集的超集或子集的信息。
        var companyTeams = new HashSet<string>() { "Ferrari", "McLaren", "Mercedes" };
        var traditionalTeams = new HashSet<string>() { "Ferrari", "McLaren" };
        var privateTeams = new HashSet<string>() { "Red Bull", "Lotus", "Toro Rosso", "Force India", "Sauber" };

        if (privateTeams.Add("Williams"))
          Console.WriteLine("Williams added");
        if (!companyTeams.Add("McLaren"))
          Console.WriteLine("McLaren was already in this set");

      IsSubsetOf验证traditionalTeams中的每个元素是否都包含在companyTeams中
        if (traditionalTeams.IsSubsetOf(companyTeams))
        {
          Console.WriteLine("traditionalTeams is subset of companyTeams");
        }
      IsSupersetOf验证traditionalTeams中是否有companyTeams中没有的元素
        if (companyTeams.IsSupersetOf(traditionalTeams))
        {
          Console.WriteLine("companyTeams is a superset of traditionalTeams");
        }
      Overlaps验证是否有交集
        traditionalTeams.Add("Williams");
        if (privateTeams.Overlaps(traditionalTeams))
        {
          Console.WriteLine("At least one team is the same with the traditional " +
          "and private teams");
        }
      调用UnionWith方法把新的 SortedSet<string>变量填充为companyTeams,privateTeams,traditionalTeams的合集
        var allTeams = new SortedSet<string>(companyTeams);
        allTeams.UnionWith(privateTeams);
        allTeams.UnionWith(traditionalTeams);

        Console.WriteLine();
        Console.WriteLine("all teams");
        foreach (var team in allTeams)
        {
          Console.WriteLine(team);
        }

        输出(有序的):
          Ferrari
          Force India
          Lotus
          McLaren
          Mercedes
          Red Bull
          Sauber
          Toro Rosso
          Williams
      每个元素只列出一次,因为集只包含唯一值。

      ExceptWith方法从ExceptWith中删除所有私有元素
        allTeams.ExceptWith(privateTeams);
        Console.WriteLine();
        Console.WriteLine("no private team left");
        foreach (var team in allTeams)
        {
          Console.WriteLine(team);
        }

  • 相关阅读:
    别让暑假留下遗憾,让我们一起去黑龙潭耍水祈福吧
    黑龙潭亲子福利:参加亲子活动合影拿好礼
    黑龙潭,北京夏日养生旅游的首选之地
    黑龙潭,一个夏日亲子游的好地方
    黑龙潭,北京真龙的栖身之所?
    密云黑龙潭周末自驾游
    白天,你陪我黑龙潭戏水观瀑;夜晚,我陪你云蒙山数星看月
    北京黑龙潭旅游攻略
    亲爱的,让我们今生约定每年都去一次黑龙潭,好吗?
    成都飞客文化2014新春贺词:感恩有你,共创辉煌
  • 原文地址:https://www.cnblogs.com/afei-24/p/6835365.html
Copyright © 2011-2022 走看看