集合类Array List HashTable实例操作练习

集合常用操作添加、遍历、移除
命名空间System.Collections

ArrayList 可变长度数组,使用类似于数组
属性 Capacity Count
方法
Add() AddRange() Remove() RemoveAt() Clear()
Contains() ToArray()
Hashtable 键值对(KeyValuePair)的集合,类似于字典

a、ArrayList对值类型的操作


代码如下:

using System;
using System.Collections;
namespace _08_ArrayList {
//ArayList对值类型的操作
class Program {
static void Main( string[] args) {
//ArrayList与数组没多大的区别 优点在于不像数组需规定长度 缺点是数据类型不限制 什么类型数据都可以放入 这样会出现许多错误
ArrayList arylist = new ArrayList();
//ArrayList添加
arylist.Add(1000);
//arylist.Add("张三");//参数类型为object 所以可以添加多种类型的参数 取出时同样需要类型转换
arylist.Add(3000);
arylist.Add(4000); //发生装箱操作 将值类型转换引用类型
arylist.Add(5000);
int [] arr = { 1, 2, 3, 4 };
arylist.AddRange(arr); //AddRange参数是实现了ICollections接口的对象 可以一次性添加数组、array、ArrayList等实现接口的对象
//集合中元素个数 使用Count = 数组Length
Console .WriteLine("集合内容长度" + arylist.Count);
//Capacity为集合的容量 是可变的 一般*2增长
Console .WriteLine(arylist.Capacity);
//访问集合第一个元素
int firstlist = Convert .ToInt32(arylist[0]);
Console .WriteLine(firstlist.ToString());
//ArrayList遍历
int sum2 = 0;
for (int i = 0; i < arylist.Count; i++) {
//sum2 += Convert.ToInt32(arylist[i]);//发生拆箱操作
Console .WriteLine(arylist[i].ToString());
}
foreach (object item in arylist) {
sum2 += Convert .ToInt32(item);
}
Console .WriteLine(sum2);
//ArrayList移除 只是移除 不是删除
arylist.Remove(1000); //移除内容是1000的 Remove移除内部的某个对象
arylist.RemoveAt(1); //移除第二项 按索引移除
//注意 移除元素 ArrayList数组会重新分配索引 所以移除操作最好是倒叙移除元素
//如果移除所有的元素 直接使用Clear
//arylist.Clear();
if (arylist.Contains(3000)) {
Console .WriteLine("包含" );
}
//ArrayList还有ToArray()但是意义不大
//这里是在ArrayList中添加值类型 那么引用类型呢????添加Student类的对象?
Console .Read();
}
}
}

b、ArrayList对引用类型的操作


代码如下:

using System;
using System.Collections;
namespace _09_ArrayListObject {
//ArrayList对引用类型的操作
class Student {
public Student(string name, int age) {
this .name = name;
this .age = age;
}
private string name;
public string Name {
get {
return name;
}
set {
name = value ;
}
}
private int age;
public int Age {
get {
return age;
}
set {
age = value ;
}
}
}
class Program {
static void Main( string[] args) {
Student xyy = new Student( "小月月" , 14);
Student fj = new Student( "凤姐" , 18);
Student fr = new Student( "芙蓉姐姐" , 19);
Student xl = new Student( "犀利哥" , 20);
ArrayList student = new ArrayList();
student.Add(xyy); //添加 也可以使用AddRange
student.Add(fj);
student.Add(fr);
student.Add(xl);
//移除
//student.Remove(fj);//这里移除的就是对象 而不是值
//student.RemoveAt(1);//索引移除
//移除不掉fj 因为Remove后是object 按索引移除
//Student stu = new Student("凤姐", 18);
//student.Remove(stu);
//Console.WriteLine(student.Contains(stu));//false 通过索引检索 因为stu与fj地址是不一样的
//遍历
for (int i = 0; i < student.Count; i++) {
Student s = student[i] as Student; //因为添加前发生装箱操作 所以 现在需要拆箱 student[i]是不能点出name的
Console .WriteLine(s.Name);
}
ArrayList ary = new ArrayList();
ary.Add( "凤姐" );
ary.Add( "小月月" );
//string类同样是引用类型 但是这里有些特别
string name = "凤姐" ;
Console .WriteLine(ary.Contains(name));//string比较的是内容 所以返回true
//根据学生姓名 获取学生对象 虽然ArrayList可以实现 但是相当的复杂 而且效率低下 所以接下来学习HashTable
Console .Read();
}
}
}

c、HashTable


代码如下:

using System;
using System.Collections;
namespace _10_HashTable {
class Student {
public Student(string name, int age) {
this .name = name;
this .age = age;
}
private string name;
public string Name {
get {
return name;
}
set {
name = value ;
}
}
private int age;
public int Age {
get {
return age;
}
set {
age = value ;
}
}
}
class Program {
static void Main( string[] args) {
//仍然使用Student的类来实现
//Hashtable键值对形式 key value 相当于字典 能根据学生的姓名快速的找到对象
Student xyy = new Student( "小月月" , 14);
Student fj = new Student( "凤姐" , 18);
Student fr = new Student( "芙蓉姐姐" , 19);
Student xl = new Student( "犀利哥" , 20);
Hashtable student = new Hashtable();
student.Add( "小月月" , xyy);
student.Add( "凤姐" , fj);
student.Add( "芙蓉姐姐" , fr);
student.Add( "犀利哥" , xl);
//student.Add("犀利哥",xl);//错误 字典中的关键字key 不允许重复 所以不能再添加犀利哥
//移除 因为没有索引 所以没有RemoveAt()
student.Remove( "小月月" );//根据key来移除
student.Clear();
student.ContainsKey( "凤姐" );//判断是不是含有这个键
//遍历 因为字典没有索引 所以不能使用for来遍历 只能使用foreach
//按key遍历 经常用
foreach (object key in student.Keys) {
Student stu = student[key] as Student;
Console .WriteLine(key);
Console .WriteLine(stu.Age);
}
//按value遍历
foreach (object value in student.Values) {
Student stu = value as Student;
if (stu != null ) {
Console .WriteLine(stu.Age);
}
}
//如果不按key 也不按value遍历 对字典遍历就是对字典的键值对进行遍历
foreach (DictionaryEntry de in student) {
Console .WriteLine(de.Key);
Student s = de.Value as Student; //因为得到的是object类型 所以 还需要转换才可以使用
Console .WriteLine(s.Age);
}
Student s2 = student["小月月" ] as Student ;//通过姓名找到该对象 获取其他的属性
if (s2 != null ) {
Console .WriteLine(s2.Age);
}
Console .Read();
}
}
}

d、练习


代码如下:

using System;
using System.Collections;
namespace _11_ArrayList练习 {
class Program {
//还是那句话 理解题目之后 有了思路再开始写code 思路最重要
static void Main( string[] args) {
//两个集合{ “a”,“b”,“c”,“d”,“e”}和{ “d”, “e”, “f”, “g”, “h” },把这两个集合去除重复项合并成一个
ArrayList ary1 = new ArrayList { "a" , "b" , "c", "d" , "e" };
ArrayList ary2 = new ArrayList { "d" , "e" , "f", "g" , "h" };
//遍历两个集合
for (int i = 0; i < ary2.Count; i++) { //循环遍历ary2元素与ary1逐个比较 如果存在相同值 则不添加 否则追加到ary1中
if (!ary1.Contains(ary2[i])) {//有Contains方法 如果没有 不知道有多复杂
ary1.Add(ary2[i]);
}
}
foreach (object item in ary1) {
Console .Write(item);
}
//随机生成10个1-100之间的数放到ArrayList中,要求这10个数不能重复,并且都是偶数
ArrayList arylist = new ArrayList();
//int numCount = 0;
while (true ) {
Random ran = new Random();
int num = ran.Next(1, 100);
if (num % 2 == 0 && !arylist.Contains(num)) { //添加!arylist.Contains(num)这句话 解决以下问题
arylist.Add(num); //为什么直接运行总显示第一个满足条件数值 而单步调试却显示正确结果???
}
if (arylist.Count == 10) {
break ;
}
}
foreach (object item in arylist) {
Console .WriteLine(item);
}
//有一个字符串是用空格分隔的一系列整数,写一个程序把其中的整数做如下重新排列打印出来:奇数显示在左侧、偶数显示在右侧。比如‘2 7 8 3 22 9'显示成‘7 3 9 2 8 22
string str = "2 7 8 3 22 9" ;
ArrayList ary3 = new ArrayList();
ArrayList ary4 = new ArrayList();
string [] s = str.Split(' ' );
foreach (var item in s) {
if (Convert .ToInt32(item) % 2 == 0) {
ary4.Add(item);
} else {
ary3.Add(item);
}
}
ary3.AddRange(ary4); //因为ary1类型为object 所以无法使用string类的join方法实现字符拼接 后面学过泛型集合可以处理
string newstr = ary3[0].ToString();//简单方式去掉空格
for (int i = 1; i < ary3.Count; i++) {
newstr += " " + ary3[i];
}
Console .WriteLine("原字符串:{0},筛选后的字符串{1}" , str, newstr + "test" );
Console .Read();
}
}
}

(0)

相关推荐

  • C#中DataSet转化为实体集合类的方法

    本文实例讲述了C#中DataSet转化为实体集合类的方法,分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: /// <summary> /// DataSet转换为实体类 /// </summary> /// <typeparam name="T">实体类</typeparam> /// <param name="p_DataSet">DataSet</param> /// <

  • SQL集合函数中case when then 使用技巧

    那么在集合函数中它有什么用呢 ? 假设数据库有一张表名为student的表. 如果现在要你根据这张表,查出江西省男女个数,广东省男生个数,浙江省男女个数 怎么写SQL语句?即要生成下结果表 答案是:select sex ,count ( case province when '广东省' then '广东省' end )as 广东省 ,count ( case province when '江西省' then '江西省' end )as 江西省 ,count ( case province whe

  • js正则函数match、exec、test、search、replace、split使用介绍集合

    match 方法 使用正则表达式模式对字符串执行查找,并将包含查找的结果作为数组返回. stringObj.match(rgExp) 参数 stringObj 必选项.对其进行查找的 String 对象或字符串文字. rgExp 必选项.为包含正则表达式模式和可用标志的正则表达式对象.也可以是包含正则表达式模式和可用标志的变量名或字符串文字. 其余说明与exec一样,不同的是如果match的表达式匹配了全局标记g将出现所有匹配项,而不用循环,但所有匹配中不会包含子匹配项. 例子1: functi

  • Python中集合类型(set)学习小结

    set 是一个无序的元素集合,支持并.交.差及对称差等数学运算, 但由于 set 不记录元素位置,因此不支持索引.分片等类序列的操作. 初始化 复制代码 代码如下: s0 = set() d0 = {} s1 = {0} s2 = {i % 2 for i in range(10)} s = set('hi') t = set(['h', 'e', 'l', 'l', 'o']) print(s0, s1, s2, s, t, type(d0)) 运行结果: 复制代码 代码如下: set() {

  • Swift教程之集合类型详解

    Swift 提供两种集合类型来存储集合,数组和字典.数组是一个同类型的序列化列表集合.字典是一个能够使用类似于键的唯一标识符来获取值的非序列化集合. 在Swift中,数组和字典的键和值都必须明确它的类型.这意味这数组和字典不会插入一个错误的类型的值,以致于出错.这也意味着当你在数组和字典中取回数值的时候能够确定它的类型. Swift 使用确定的集合类型可以保证代码工作是不会出错,和让你在开发阶段就能更早的捕获错误. note: Swift的数组 储存不同的类型会展示出不同的行为,例如变量,常量或

  • 集合类List与Dictonary实例练习

    a.List<>泛型集合 复制代码 代码如下: View Code using System; using System.Collections.Generic; namespace _02_泛型集合 { class Person { public Person(string name, int age) { this .name = name; this .age = age; } private string name; public string Name { get { return

  • Java中的collection集合类型总结

    Java集合是java提供的工具包,包含了常用的数据结构:集合.链表.队列.栈.数组.映射等.Java集合工具包位置是java.util.* Java集合主要可以划分为4个部分:List列表.Set集合.Map映射.工具类(Iterator迭代器.Enumeration枚举类.Arrays和Collections). Java集合工具包框架如下图. 说明:看上面的框架图,先抓住它的主干,即Collection和Map. Collection是一个接口,是高度抽象出来的集合,它包含了集合的基本操作

  • 使用Enumeration和Iterator遍历集合类详解

    前言在数据库连接池分析的代码实例中,看到其中使用Enumeration来遍历Vector集合.后来就找了一些资料查看都有哪些方法可以遍历集合类,在网上找到了如下的使用Enumeration和Iterator遍历集合类的实例.不过这个实例中提到了Enumeration比Iterator的效率更高,其实并不是这样子的,该实例是的时间测试太片面了, 因为数据量太少.随着数据两的增加,两者之间的效率越来越接近,而不会出现倍数的比例.而且现在普遍都使用Iterator来遍历集合类,只有特别明确声明必须使用

  • C++简单集合类的实现方法

    来自于C++程序设计的一个题目.实现一个集合类,要求实现以下4个操作.  1.向集合中添加元素,如果集合中已存在元素则不添加  2.从集合中移除元素,移除之前需要先判断集合中元素是否存在  3.重载+运算符,用以实现集合的求并集运算  4.重载*运算符,用以实现集合的求交集运算 1.类的整体设计 该问题需要模拟实现集合类,我们可以使用数组来模拟集合,于是使用int items[100]用来存放集合中的数据.为了实现数组的遍历,这就需要一个整数用来表示数组中元素的个数,于是使用int number

  • Python set集合类型操作总结

    Python中除了字典,列表,元组还有一个非常好用的数据结构,那就是set了,灵活的运用set可以减去不少的操作(虽然set可以用列表代替) 小例子 1.如果我要在许多列表中找出相同的项,那么用集合是最好不过的了,用集合只用一行就可以解决 复制代码 代码如下: x & y & z # 交集 2.去重 复制代码 代码如下: >>> lst = [1,2,3,4,1] >>> print list(set(lst)) [1, 2, 3, 4] 用法 注意se

随机推荐