使用HashSet 创建整数集
我想创建一个使用HashSet
表示整数集的类。 我希望它使用该内部容器跟踪集合中包含的值。 到目前为止我做到了这一点:
class SetInteger { HashSet intTest= new HashSet(); intTest.Add(1); intTest.Add(2); intTest.Add(3); intTest.Add(4); intTest.Add(5); intTest.Add(6); intTest.Add(7); intTest.Add(8); intTest.Add(9); intTest.Add(10); }
所以,在这里我想我正在为HashSet
添加一些值,但是我没有看到它如何跟踪集合中包含的值。 有任何想法吗?
哈希集有一个Contains
方法,允许您检查值是否在集合中。
此外, HashSet
实现了ISet
接口,因此提供了许多用于处理集合的方法,例如并集和交叉,并确定一组值是否是(适当的)超集或子集。
HashSet intTest = new HashSet () { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; bool has4 = intTest.Contains(4); // Returns true bool has11 = intTest.Contains(11); // Returns false bool result = intTest.IsSupersetOf(new []{ 4, 6, 7 }); // Returns true
顺便问一下,你知道集合初始化器的语法吗?
您还可以预设集合以获取它包含的每个元素(以未指定的顺序):
foreach(int value in intTest) { // Do something with value. }
或者将其转换为数组或可变列表(也以未指定的顺序):
int[] arr = intTest.ToArray(); List lst = intTest.ToList();
嗯……好吧, HashSet
实现了IEnumerable
,所以你总是可以做到这一点来弄清楚“那里已有什么”:
HashSet intTest= new HashSet (); intTest.Add(1); intTest.Add(2); intTest.Add(3); intTest.Add(4); intTest.Add(5); intTest.Add(6); intTest.Add(7); intTest.Add(8); intTest.Add(9); intTest.Add(10); var inThereNow = intTest.ToArray(); // [1,2,3,4,5,6,7,8,9,10]
还有bool Contains(T value)
会告诉你一个特定值是否在集合中, IEnumerable
会告诉你两个集合的“OR”, IEnumerable
它将告诉你两个集合的重叠……在IEnumerable
或ISet
几乎任何东西
如果值已经存在,您可以使用HashSet Contains
方法告诉我们!
示例:
if (intTest.Contains(5)) { // already has the value }
我们的Contains方法: http : //msdn.microsoft.com/en-us/library/bb356440.aspx
希望这可以帮助。
你可以试试这个。 你只需要一个文本框和两个按钮。
HashSet hs = new HashSet (); private void savedataonhashSet_Click(object sender, EventArgs e) { hs.Add(Convert.ToInt16(textBox1.Text)); } private void checkduplicatevalue_Click(object sender, EventArgs e) { if (hs.Contains(00)) { MessageBox.Show("it is"); } else { MessageBox.Show("not there"); } }
如果你再次遇到问题只需丢弃你的代码…..
上述就是C#学习教程:使用HashSet 创建整数集分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/954392.html