C#集合之集(set)

來源:互聯網
上載者:User

標籤:add   and   err   dia   子集   team   ast   重複元素   new   

  包含不重複元素的集合稱為“集(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);
    }

C#集合之集(set)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.