C#常用算法:集合2013-11-14集合类型的数据结构在日常编程中占重要比例,大多数的业务需求都需要用到集合类型的数据结构。.NET平台为我们提供了种类繁多的集合类型的数据结构,我们只需要简单的调用相应的API就能完成对零散数据的整理。本文收集了目前.NET平台下为我们提供的所有集合类型,并提供一个小例子。IEnumerable
namespace System.Collections.Generic{public interface IEnumerable<out T> : IEnumerable{IEnumerator<T> GetEnumerator();}}
public static void EnumerableTest(){List<string> tmp = new List<string>();tmp.Add("Apple");tmp.Add("Grape");tmp.Add("Watermelon");strEnumerable = tmp as IEnumerable<string>;if (tmp != null){var iterator=strEnumerable.GetEnumerator();while (iterator.MoveNext()){Console.WriteLine(iterator.Current);}}/*OUTPUTAppleGrapeWatermelon*/}
ICollection
namespace System.Collections.Generic{public interface ICollection<T> : IEnumerable<T>, IEnumerable{bool IsReadOnly { get; }void Clear();void CopyTo(T[] array, int arrayIndex);bool Remove(T item);}}
public static void CollectionTest(){ List<int> sourceTable=new List<int>();sourceTable.Add(69);sourceTable.Add(57);sourceTable.Add(87);intCollection = sourceTable as ICollection<int>;if (intCollection != null){Console.WriteLine("Current collection has {0} elements totally", intCollection.Count);var iterator = intCollection.GetEnumerator();while (iterator.MoveNext()){Console.WriteLine(iterator.Current);}}/*OUT PUT Current collection has 3 elements totally 69 57 87*/}