C# 集合(四) —— Set类

总目录
C# 语法总目录

集合四 Set

  • [1. Set](#1. Set)

1. Set

有 HashSet 和 SortedSet,

  • 它们都不包含重复元素
  • 忽略添加重复值的请求
  • 无法根据位置访问元素
  • 使用Contains方法均使用散列查找,所以速度快

SortedSet 按照一定顺序保存元素,使用红黑树实现,而HashSet是根据Hash值保存元素和查找元素。

csharp 复制代码
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();

for (int i = 0; i < 5; i++)
{
    // Populate numbers with just even numbers.
    evenNumbers.Add(i * 2);

    // Populate oddNumbers with just odd numbers.
    oddNumbers.Add((i * 2) + 1);
}

foreach (var item in evenNumbers)
{
    Console.WriteLine(item);
}
Console.WriteLine("--------------------------");

foreach (var item in oddNumbers)
{
    Console.WriteLine(item);
}
Console.WriteLine("--------------------------");
csharp 复制代码
HashSet<int> numbers = new HashSet<int>(evenNumbers);
foreach (var item in numbers)
{
    Console.WriteLine(item);
}
Console.WriteLine("--------------------------");
numbers.UnionWith(oddNumbers);

foreach (var item in numbers)
{
    Console.WriteLine(item);
}
csharp 复制代码
/*
2
4
6
8
--------------------------
1
3
5
7
9
--------------------------
0
2
4
6
8
--------------------------
0
2
4
6
8
1
3
5
7
9
*/

总目录
C# 语法总目录

相关推荐
Scout-leaf2 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530143 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools4 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的4 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21884 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
lindexi4 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言