C#集合。

集合命名空间:

  using system.collections. 非泛型集合

  using system.collections.Generic.  泛型集合

为什么要用集合:

  1、数组一旦声明长度就固定了。

  2、集合有很多方法可以用

  等

常用集合:

类似数组集合:ArrayList  List<>

键值对集合:Hashtable  Dictionary<K V>

栈集合:Stack

队列:Queye

ArrayList:

 class Program{      static void Main(string[] args){ArrayList arrayList = new ArrayList();arrayList.Add(1); //增加一个元素arrayList.AddRange(new int[] { 2, 3 });//增加一个集合arrayList.Insert(0, "开始:");//在指定位子插入一个元素arrayList.InsertRange(4, new string[] { "", "", "" });//指定位置插入集合arrayList.RemoveAt(7);arrayList.Clear();//清空集合for (int i = 0; i < arrayList.Count; i++){Console.WriteLine(arrayList[i]);}}    }

Remove()不是根据对象来判断的,而是根据值来判断。

Contains()是否包含某个值,也是根据值来判断的。

集合转为数组:.ToArray().

排序:  1、.sort() 升序  没有降序   可以用.Reverse()颠倒位置实现。

    2、想让任何集合实现排序需要实现 IComparable接口 。

    3、直接调用sort是使用ICompareble 接口的默认方式来排序。可以用sort的重载,使用自己的比较器。

Hashtable:

简单添加和获取:

class Program{      static void Main(string[] args){Hashtable hashtable = new Hashtable();hashtable.Add("Sam", "Sam");hashtable.Add("Penny", new Person() { Name = "Penny" });Console.WriteLine(hashtable["Sam"]);Person Penny = hashtable["Penny"] as Person;Console.WriteLine(Penny.Name);}    }

键值对集合的键不能重复。

判断是否存在某个键:.ContentsKey()    是否存在某个值:.ContentsValue()

遍历Hash table:

class Program{      static void Main(string[] args){Hashtable hashtable = new Hashtable();hashtable.Add("Sam", "Sam");hashtable.Add("Penny", "Penny");//遍历键foreach (object item in hashtable.Keys){Console.WriteLine("Key:{0}----Value:{1}",item,hashtable[item]);}//遍历值foreach (object item in hashtable.Values){Console.WriteLine("Value:{0}",item);}//遍历键值对foreach (DictionaryEntry item in hashtable){Console.WriteLine("Key:{0}---Value{1}",item.Key,item.Value);}}    }

集合小练习:

两个ArrryList集合的并集。

class Program{      static void Main(string[] args){ArrayList A = new ArrayList(new string[] {"a","b"});ArrayList B = new ArrayList(new string[] { "a", "b","c","d" });for (int i = 0; i <B.Count; i++){if (!A.Contains(B[i])){A.Add(B[i]);}}for (int i = 0; i < A.Count; i++){Console.WriteLine(A[i]);}}    }

随机生成十个1-100之间的数放到arraylist中,这些数必须是偶数且不能重复。

class Program{      static void Main(string[] args){ArrayList arrayList = new ArrayList();Random random = new Random();while (arrayList.Count<10){int r = random.Next(1, 101);if (!arrayList.Contains(r)&&((r%2)==0)){arrayList.Add(r);}}for (int i = 0; i < arrayList.Count; i++){Console.WriteLine(arrayList[i]);}}    }

上面程序把random放循环外面效率更好,因为无参的random构造函数以系统时间为种子,而一遍循环完了以后时间还没来得及变,就会生成相同的数。

泛型集合: 

List<string> list = new List<string> () 

和 arraylist相比:

  数据类型固定,有更多的方法可以用。

Dictionary<string, int> dic = new Dictionary<string, int> ;

和hashtable相比:

  键和值都有类型约束。

遍历键值对:

 class Program{      static void Main(string[] args){Dictionary<string, int> dic = new Dictionary<string, int>();dic.Add("Sam", 22);dic.Add("Penny", 23);foreach (KeyValuePair<string,int> item in dic){Console.WriteLine("keys:{0}--value:{1}",item.Key,item.Value);}}    }

判断字符串中每个字母出现的次数:

class Program{      static void Main(string[] args){string str = "wellcome to china";Dictionary<char, int> dict = new Dictionary<char, int>();for (int i = 0; i < str.Length; i++){if (char.IsLetter(str[i])){if (dict.ContainsKey(str[i])){dict[str[i]]++;}else{dict.Add(str[i], 1);}}}foreach (KeyValuePair<char,int> item in dict){Console.WriteLine("{0}----{1}",item.Key,item.Value);}}    }

 

转载于:https://www.cnblogs.com/zhangyuhao/p/10518935.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/463176.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

对std::listT的封装

由于工作的原因&#xff0c;需要在线程安全的情况下对std::list<T>进行该list进行访问&#xff0c;因此就简单的封装了下&#xff0c;代码如下&#xff1a; template<typename T> class List { public:List () {}~List () {}void PushBack(const T& value) {b…

code

// 控制字体系列。"editor.fontFamily": "Droid Sans Mono, monospace, monospace, Droid Sans Fallback",// 覆盖当前所选颜色主题中的编辑器颜色和字体样式。"editor.tokenColorCustomizations": {},// 控制差异编辑器是否将对前导空格或尾随空…

SWISHMAX2脚本整理及Swishmax使用技巧

wish Max让你更快速更简单地在你的网页中加入Flash动画,超过230种可选择的预设效果.SWiSH是一个快速、简单且经济的方案,让你可以在你的网页 中加入Flash动画.只要点几下鼠标,你就可以加入让你的网页在众多网站中令人注目的酷炫动画效果.你可以创造形状、文字、按钮以及移动路径…

MAC机路由管理

On the Mac the command is similar, but a bit different Just as a note to myself and anyone else interested:add network:1sudo route add -net 10.67.0.0/16 192.168.120.254Add hostsudo route add -host 10.67.0.0/16 192.168.120.254转载于:https://blog.51cto.com…

Redis的持久化机制

Redis 的数据全部在内存里&#xff0c;如果突然宕机&#xff0c;数据就会全部丢失&#xff0c;因此必须有一种机制来保证 Redis 的数据不会因为故障而丢失&#xff0c;这种机制就是 Redis 的持久化机制。 Redis 的持久化机制有两种&#xff0c;第一种是RDB快照&#xff0c;第二…

今天用python的turtle简单画了一副眼镜

画的不太好看&#xff0c;下次要继续努力鸭!!! 这个是代码~ 1 from turtle import*2 pencolor("blue")3 fillcolor("white")4 setup(500,1000,100,10)5 speed(2)6 pensize(4)7 begin_fill()8 circle(40,450)9 goto(70,40) 10 circle(-40,360) 11 penup() 1…

怎么样能找到国外的群?

怎么样能找到国外的群和老外聊天,学习呢&#xff1f;给你条途径。 先申请个MSN&#xff0c;作为固定的聊天基地。 在去WWW.OICQ.COM。 这是个外国的聊天网址&#xff0c;去那边的聊天室&#xff08;临时聊天基地&#xff0c;用来找新网友&#xff09;聊天。若是有个谈的来的&am…

redis RDB持久化中save和bgsave区别

SAVE 和 BGSAVE 两个命令都会调用 rdbSave 函数&#xff0c;但它们调用的方式各有不同&#xff1a; SAVE 直接调用 rdbSave &#xff0c;阻塞 Redis 主进程&#xff0c;直到保存完成为止。在主进程阻塞期间&#xff0c;服务器不能处理客户端的任何请求。BGSAVE 则 fork 出一个…

OA系统

employee对象为空&#xff0c;所以mybatis无法获取employeeId的值 getProperty(null, "employeeId") null是employee对象&#xff0c;employeeId是employee对象的属性 Struts Problem Report Struts has detected an unhandled exception: Messages: source is null …

合并所有文档

合并所有文档type *.txt >index.txt #将所有.txt文件内容合并到index.txt文件中 转载于:https://www.cnblogs.com/juan-F/p/10532455.html

memmove()/mmecpy()

今天用到了memcpy()库函数&#xff0c;然后自己实现了一个结合源码应该是这样的 ​ void *memmove(void *dest, const void *src, size_t count) {assert((NULL ! dest) && (NULL ! src) && (count > 0));char *pdest (char *)dest;const char *psrc (co…

ADHD-注意力缺陷多动症

【以下内容转自Wiki】 ADHD&#xff1a;Attention deficit-hyperactivity disorder ADHD的主要病征是&#xff1a; 注意力散涣&#xff08;inattentive&#xff09;或 集中困难&#xff08;Attention-deficit&#xff09;活动量过多&#xff08;hyperactive或hyperkinetic&…

2019春季第三次编程总结

7-1 判断上三角矩阵 &#xff08;15 分) 上三角矩阵指主对角线以下的元素都为0的矩阵&#xff1b;主对角线为从矩阵的左上角至右下角的连线。 本题要求编写程序&#xff0c;判断一个给定的方阵是否上三角矩阵。 输入格式&#xff1a; 输入第一行给出一个正整数T&#xff0c;为待…

memcmp()库函数实现

今天用到了memcpy()库函数&#xff0c;自己实现了一个&#xff0c;如下&#xff1a; int memcmp(const void *str1, const void *str2, size_t count) {assert((NULL ! str1) && (NULL ! str2));const char *pstr1 (const char*)str1;const char *pstr2 (const char*…

ZerMQ安装与使用

windows下 使用vs2010的&#xff0c;v4.0.4的版本官方 0mq api 好像还没加上去&#xff0c;我是参照老版本&#xff08;v3.1)的用法来的。 使用前你要对windows下动态库的使用有个基本了解。我的上一篇博客有讲&#xff0c;但有点乱&#xff0c;有时间再改一改。 这里我是用了…

远程客户端连接MysqL数据库太慢解决方案

为什么80%的码农都做不了架构师&#xff1f;>>> 局域网客户端访问mysql 连接慢问题解决。 cd /etc/mysql vi my.conf [mysqld] skip-name-resolve 此选项禁用了DNS解析&#xff0c;连接速度会快很多。不过&#xff0c;这样的话就不能在MySQL的授权表中使用主机名了…

系统编程第三次上机

先把题目和百度到的参考资料粘过来吧orz 弱智答案等ddl过了再粘上来 一是怕错误的答案误导大家&#xff0c;二是怕查重QAQ 实验目的 掌握shell中管道、重定向的用法 学习shell基本语法 进阶内容 注&#xff1a;本部分内容不作为实验必须要求&#xff0c;只是作为对有兴趣深入学…

动态添加模板列及保持页面状态

前台 HTML code <form id"form1"runat"server"><asp:GridView ID"GridView1"runat"server"AutoGenerateColumns"False"><EmptyDataTemplate><asp:Label ID"Label1"runat"server"…

C语言base64编解码

base64码简介 Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一&#xff0c;大家可以查看RFC2045&#xff5e;RFC2049&#xff0c;上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。例如&#xff0c;在Java Persistence系统Hibernate中&#…

学号 20175212 《Java程序设计》第3周学习总结

学号 20175212 《Java程序设计》第3周学习总结 教材学习内容总结 一、 Java——面向对象语言 核心内容为对象&#xff0c;一切围绕着对象。以下为三个重要性质&#xff1a; 封装性&#xff1a;将数据和对数据的操作封装在一起。继承&#xff1a;子类可以继承父系的属性和行为。…