日期:2014-05-16  浏览次数:20972 次

C# 关于集合
关于集合
集合主要用于数据存储和检索,.net中的集合提供了支持堆栈,队列,链表,哈希表,大多数集合实现相同的接口,可以继承这些接口来创建更为专业的新集合类。


泛型集合,非泛型集合对比:
.net中的定义集合分为泛型,非泛型。非泛型的在空间System.Collections,泛型的在System.Collections.Generic中。
非泛型集合类的类型是System.Object类,因此它的类型比较弱,而泛型集合可以提供更高的类型安全性,因此具有更好的性能。
非泛型集合如果想提供强类型实现,要从基集合类型派生并且实现特定的成员,这比较麻烦。


集合接口:
集合类大多都派生于ICollection、IComparer、IEnumerable、IList、IDictionary 和 IDictionaryEnumerator 。


常见的集合类型:
<1>Array
public abstract class Array : ICloneable,IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
Array是一个抽象类,里面提供了很多静态方法,只有system,编译器能够显式的继承它,Array类是支持数组的语言实现的基类,也就是说C#中的数组是从Array类继承的。数组是从Array类继承的引用类型。
我们知道对一个数组来说,其常用的操作有“创建初始化”,"复制",“查找”,“索引”,“设置值”,“排序”。下面一一举出常用函数。
创建:
CreateInstance(Type, Int32)	//创建一个指定长度的一维数组
CreateInstance(Type, Int32[])	//创建一个多维数组,多维数组的长度在Int32[]中指定
CreateInstance(Type, Int64[])	//创建一个多维数组,多维数组的长度在Int64[]中指定	
CreateInstance(Type, Int32, Int32)		//创建一个具有指定维长的2维数组
CreateInstance(Type, Int32[], Int32[])		//创建具有指定下限,指定长度的多维数组
CreateInstance(Type, Int32, Int32, Int32)	//创建一个3维数组

复制:
Copy(Array A, Array B, Int32 n)	//把A中从第一个元素开始的n个元素复制到B中
Copy(Array, Array, Int64)
Copy(Array A, Int32 start, Array B, Int32 start, Int32)	//把A中从start开始的n个元素复制到B中从start开始的元素
Copy(Array, Int64, Array, Int64, Int64)
CopyTo(Array B, Int32 start)	//把对象中所有的元素复制到B中从start开始的元素
CopyTo(Array, Int64)

查找:
public static T Find<T>( T[] array, Predicate<T> match) //查找满足match条件的元素并返回第一个符合条件的元素
示例如下:
public class Example
{
    public static void Main()
    {
        Point[] points = { new Point(100, 200), new Point(150, 250), new Point(250, 375), 
            new Point(275, 395), new Point(295, 450) };


        Point first = Array.Find(points, ProductGT10);


        // Display the first structure found.
        Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
    }


    // This method implements the test condition for the Find method.
    private static bool ProductGT10(Point p)
    {
        if (p.X * p.Y > 100000)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


//	output:


//	Found: X = 275, Y = 395


FindAll<T>	//返回符合查询条件的所有元素的数组
FindIndex<T>(T[] A, Predicate<T> e)	//从数组A中找到符合条件e的首个元素的索引并返回
FindIndex<T>(T[] A, Int32 s, Predicate<T> e)	//从数组A中索引s开始找到符合条件e的元素并返回
FindIndex<T>(T[] A, Int32 s, Int32 l, Predicate<T> e)	//从数组A中以索引s开始,长度为l,找到符合条件e的首个元素索引并返回
FindLastIndex<T>(T[], Predicate<T>)
FindLastIndex<T>(T[], Int32, Predicate<T>)
FindLastIndex<T>(T[], Int32, Int32, Predicate<T>)




获取数组相关属性
GetLength	//获取数组长度
public int GetLowerBound(int dimension)	//获取指定维度的数组的下限
public int GetUpperBound(int dimension)	//获取指定维度的数组的上限
public Type GetType()			//获取当前实例的Type

根据索引求对象
public Object GetValue(int index)	//获取一维数组中指定索引的元素值
public Object GetValue(params int[] indices)//获取多维数组中指定索引的元素值
public Object GetValue(	int index1,int index2)
public Object GetValue(int index1,int index2,int index3)