C# 集合类自己经常用到: 数组(Array)、动态数组(ArrayList)、列表(List)、哈希表(Hashtable)、字典(Dictionary),对于经常使用的这些数据结构,做一个总结,便于以后备忘使用。
1 所在命名空间
using System.Collections.Generic;
using System.Collections;
2 List列表
List<T>表示泛型数组,主要运用 数据初始化,对数组元素的增查改删,复制,排序,倒序,是ArrayList的增强版。
2.1 初始化
//创建不同副本,zd10-01
//空的List
List<int> intlst1 = new List<int>();
List<object> intlst2 = new List<object>();
//容量为10的空列表
List<string> str1lst = new List<int>();
//5个元素
int[] ary = { 0,1,2,3,4};
List<int> intlst3 = new
List<int>(ary);
2.2 遍历
private void NavagateList(List<int> intary)
{
foreach(int intvalues in intary)
{
MessageBox.Show(intvalues.ToString());
}
}
2.3增查改删
//zd10-01
常用属性
count,Capacity
方法
增:
Add,Insert
//例
List<int> list1 = new List<int>();
//从0开始
list1.add(0);
int[] ar={1,2,3};
list1.AddRange(ar);
list1.Add(4);
//在索引1的位置插入5
list1.Insert(1,5);
//遍历
NavagateList(list1);
删:
Remove,RemoveAt,RemoveRange
//删除最后一个元素,Tail
list1.Remove(1);
list1.RemoveAt(2);
list1.RemoveRange(1,2);
搜索:
IndexOf,LastIndexOf,Find,FindLast,FindIndex
//返回指定元素在数组中第一次出现的索引
int index =list1.IndexOf(4);
private static bool IsIntOk(int val)
{
if (val>3) return
true;
return false;
}
Predicate<int> match=new Predicate<int>(IsIntOk);
list1.Find(match);
排序:
Sort,Reverse
list1.Sort();
NavagateList(list1);
//倒序
list1.Reverse();
NavagateList(list1);
原文:http://www.cnblogs.com/zoood/p/3618463.html