一、C#Set入门
C#Set是一种无序、不可重复的集合类型。使用Set可以避免重复添加相同的元素,提高代码的运行效率。在C#中,Set是通过HashSet类实现的。
创建Set对象的方法如下:
HashSet<string> set = new HashSet<string>();
上述代码创建了一个名为set的空HashSet对象。
向Set中添加元素的方法如下:
set.Add("apple"); set.Add("banana");
上述代码向set中分别添加了”apple”和”banana”两个元素。
遍历Set中的元素的方法如下:
foreach(string element in set) { Console.WriteLine(element); }
上述代码遍历了set中的所有元素,并输出它们的值。注意,输出的顺序是随机的,因为Set是无序的。
二、Set的常用方法
下面介绍Set的常用方法:
1、Add()
Add()方法用于向Set中添加元素,如果添加的元素已经存在,则不执行任何操作。
HashSet<int> set = new HashSet<int>(); set.Add(1); // 添加元素1到Set中 set.Add(2); // 添加元素2到Set中 set.Add(1); // Set中已经存在元素1,所以这一行代码不会生效
2、Remove()
Remove()方法用于从Set中移除指定的元素。
HashSet<string> set = new HashSet<string>(); set.Add("apple"); set.Add("banana"); set.Remove("apple"); // 从Set中移除元素"apple"
3、Contains()
Contains()方法用于判断Set中是否包含指定的元素。
HashSet<string> set = new HashSet<string>(); set.Add("apple"); set.Add("banana"); bool containsApple = set.Contains("apple"); // containsApple的值为true bool containsOrange = set.Contains("orange"); // containsOrange的值为false
4、Count
Count属性用于获取Set中元素的个数。
HashSet<int> set = new HashSet<int>(); set.Add(1); set.Add(2); int count = set.Count; // count的值为2
5、Clear()
Clear()方法用于清空Set中的所有元素。
HashSet<string> set = new HashSet<string>(); set.Add("apple"); set.Add("banana"); set.Clear(); // 清空Set中的所有元素
三、其他相关知识点
1、C#中的Dictionary和Set的区别
C#中的Dictionary和Set都是集合类型,它们非常相似,但也有一些区别:
- Dictionary是键值对的集合,每个元素都包含一个键和一个值;而Set只是一个元素的集合,没有键值对的概念。
- Dictionary使用Add()方法向其中添加元素,需要同时指定键和值;而Set只需要指定元素即可。
2、C#中的HashSet和List的区别
HashSet和List都是集合类型,但它们的实现方式有所不同,也有一些区别:
- HashSet是无序的、不可重复的集合,而List是有序的、可重复的列表。
- 向HashSet中添加元素时,会自动去重;而向List中添加元素时,不会去重。
- HashSet中的查找和删除操作比List更高效。
四、使用C#Set的实例
1、获取数组中的不重复元素
以下代码展示如何使用Set获取数组arr中的不重复元素:
int[] arr = new int[] {1, 2, 3, 2, 4, 3, 5}; HashSet<int> set = new HashSet<int>(arr); foreach(int element in set) { Console.WriteLine(element); }
输出结果为:
1 2 3 4 5
2、使用Set进行去重
以下代码展示如何使用Set对列表list中的元素进行去重:
List<string> list = new List<string>() {"apple", "banana", "orange", "banana"}; HashSet<string> set = new HashSet<string>(list); foreach(string element in set) { Console.WriteLine(element); }
输出结果为:
apple banana orange
3、获取两个数组中的共同元素
以下代码展示如何使用Set获取数组arr1和数组arr2中的共同元素:
int[] arr1 = new int[] {1, 3, 5, 7, 9}; int[] arr2 = new int[] {2, 4, 6, 8, 10, 1, 5, 9}; HashSet<int> set1 = new HashSet<int>(arr1); HashSet<int> set2 = new HashSet<int>(arr2); set1.IntersectWith(set2); foreach(int element in set1) { Console.WriteLine(element); }
输出结果为:
1 5
4、使用Set判断两个数组中是否存在相同元素
以下代码展示如何使用Set判断数组arr1和数组arr2中是否存在相同元素:
int[] arr1 = new int[] {1, 3, 5, 7, 9}; int[] arr2 = new int[] {2, 4, 6, 8, 10, 1, 5, 9}; HashSet<int> set1 = new HashSet<int>(arr1); HashSet<int> set2 = new HashSet<int>(arr2); set1.IntersectWith(set2); if(set1.Count > 0) { Console.WriteLine("数组arr1和数组arr2中存在相同元素!"); }
输出结果为:
数组arr1和数组arr2中存在相同元素!
五、总结
本文详细介绍了C#中的Set,包括Set的基本用法、常用方法、与其他集合类型的区别以及使用实例。通过阅读本文,你应该能够熟练使用C#Set来实现各种功能。
原创文章,作者:UIIGJ,如若转载,请注明出处:https://www.506064.com/n/316522.html