本人是初学菜鸟,有错误的地方欢迎大家指正。
数组:
什么是数组:
一种数据结构,可以通过计算得到索引,可以利用索引来存取的变量。
数组的类型:
一维数组,二维数组,三维数组……(多维数组)。
数组的定义:
格式:
数组元素类型(比如int等) [ ] 数组名 =new 数组元素类型(比如int等) [(数组元素个数)];
或: 数组元素类型(比如int等) [ ] 数组名 ={数组初始化的内容};
例子:
int[] a={3,1,4,2};//一维数组
int[,] b = { { 1, 2, 3, 4 }, { 1, 2, 3,4 } };//二维数组
int[][] c = { new int[1]{1},new int[2]{1,2},new int[3]{1,2,3}};//存放 数组类型 的一维数组
数组的使用:
1,根据索引访问和修改数组的元素
class Program
{
static void Main(string[] args)
{
int[] a={3,1,4,2};
int[,] b = { { 1, 2, 3, 4 }, { 1, 2, 3,4 } };
int[][] c = { new int[1]{1},new int[2]{1,2},new int[3]{1,2,3}};//存放数组的数组
for (int i = 0; i < a.Length;i++ )
Console.Write(a[i]);
foreach (int t in b)
{
Console.WriteLine(t);
}
Console.WriteLine();
for (int i=0; i < 3; i++)
{
for (int j = 0; j <= i; j++)
Console.Write(c[i][j]);
Console.WriteLine();
}
}
}
2,调用C#中有关数组的方法或属性:
1)IsFixedSize (属性):指示该数组是否是固定大小;
class Program
{
static void Main(string[] args)
{
int[] a={1,2,3,4};
Console.WriteLine(a.IsFixedSize);
}
}
2)Length(属性): 获得一个32位整数,表示数组所有维数的元素个数;
static void Main(string[] args)
{
int[] a={1,2,3,4};
Console.WriteLine(a.Length);
}
3)Rank(属性):获得数组的维数。
class Program
{
static void Main(string[] args)
{
int[] a={1,2,3,4};
Console.WriteLine(a.Rank);
}
}
4)Copy(静态方法)CopyTo(方法):将一个数组的一部分复制到另外一个数组中
class Program
{
static void Main(string[] args)
{
int[] a={1,2,3,4};
int[] b = new int[4];
a.CopyTo(b,0);
foreach(int t in b)
Console.WriteLine(t);
}
}
class Program
{
static void Main(string[] args)
{
int[] a={1,2,3,4};
int[] b = new int[4];
Array.Copy(a, b, 4);
foreach(int t in b)
Console.WriteLine(t);
}
}
5)GetLength(方法):获取一个32位整数,表示数组中指定维数的元素个数。
class Program
{
static void Main(string[] args)
{
int[] a={1,2,3,4};
Console.WriteLine( a.GetLength(0));
}
}
6)IndexOf/LastIndexOf (静态方法):返回数组或部分数组中,某个值第一/最后一个匹配的索引
class Program
{
static void Main(string[] args)
{
int[] a={2,2,2,2};
Console.WriteLine( Array.LastIndexOf(a, 2));
}
}
7)Sort(静态方法):对一维数组排序,默认从小到大排序
class Program
{
static void Main(string[] args)
{
int[] a={3,1,4,2};
Array.Sort(a);
foreach(int t in a)
Console.WriteLine(t);
}
}
集合:
集合类所有的属性和方法包括在接口ICollection中,要使用集合,需要引用命名空间:using System.Collections
集合的分类:
1)动态数组类ArrayList
2) 队列Queue类(先进先出)
3)堆栈类Stack类(先进后出)
4)哈希表Hashtable,键值与值对应
5)排序列表SortedList,键值与值对应,并且有序。