集合类型的数据结构在日常编程中占重要比例,大多数的业务需求都需要用到集合类型的数据结构。.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);
}
}
/*OUTPUT
Apple
Grape
Watermelon
*/
}
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
*/
}
IList
namespace System.Collections.Generic
{
public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
T this[int index] { get; set; }
void Insert(int index, T item);
void RemoveAt(int index);
}
}
public static void ListTest()
{
List<float> temperatureTable = new List<float>();
temperatureTable.Add(1.20f);
temperatureTable.Add(5.43f);
temperatureTable.Add(8.64f);
floatList = temperatureTable as IList<float>;
if (floatList != null)
{
Console.WriteLine("Current collection has {0} elements totally", floatList.Count);
var iterator = floatList.GetEnumerator();
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current);
}
}
/*OUT PUT
Current collection has 3 elements totally
1.2
5.43
8.64
*/
}
ISet
namespace System.Collections.Generic
{
public interface ISet<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
bool Add(T item);
void ExceptWith(IEnumerable<T> other);
void IntersectWith(IEnumerable<T> other);
bool IsProperSubsetOf(IEnumerable<T> other);
bool IsProperSupersetOf(IEnumerable<T> other);
bool IsSubsetOf(IEnumerable<T> other);
bool IsSupersetOf(IEnumerable<T> other);
bool Overlaps(IEnumerable<T> other);
bool SetEquals(IEnumerable<T> other);
void SymmetricExceptWith(IEnumerable<T> other);
void UnionWith(IEnumerable<T> other);
}
}
public static void SetTest()
{
无序集合HashSet
HashSet<string> charaterList = new HashSet<string>();
charaterList.Add("A");
charaterList.Add("B");
charaterList.Add("C");
if (!charaterList.Add("A"))
{
Console.WriteLine("Current Collection already have the 'A'");
}
foreach (string tmp in charaterList)
{
Console.WriteLine(tmp);
}
Console.WriteLine();
/*OUTPUT
Current Collection already have the 'A'
A
B
C
*/
有序集合SortedSet
SortedSet<string> charaterList2 = new SortedSet<string>();
charaterList2.Add("A");
charaterList2.Add("B");
charaterList2.Add("D");
charaterList2.Add("C");
charaterList2.Add("G");
charaterList2.Add("E");
charaterList2.Add("F");
if (!charaterList2.Add("A"))
{
Console.WriteLine("Current Collection already have the 'A'");
}
foreach (string tmp in charaterList2)
{
Console.WriteLine(tmp);
}
/*OUT PUT
* Current Collection already have the 'A'
A
B
C
D
E
F
G
*/
IsSubSetOf()和IsSuperSetOf()方法
//int[] onetoten = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//int[] fivetoeight = new int[] { 5, 6, 7, 8 };
HashSet<int> onetoten = new HashSet<int>();
onetoten.Add(1);
onetoten.Add(2);
onetoten.Add(3);
onetoten.Add(4);
onetoten.Add(5);
onetoten.Add(6);
onetoten.Add(7);
onetoten.Add(8);
onetoten.Add(9);
onetoten.Add(10);
HashSet<int> fivetoeight = new HashSet<int>();
fivetoeight.Add(5);
fivetoeight.Add(6);
fivetoeight.Add(7);
fivetoeight.Add(8);
HashSet<int> eleventofifteen = new HashSet<int>();
eleventofifteen.Add(11);
eleventofifteen.Add(12);
eleventofifteen.Add(13);
eleventofifteen.Add(14);
eleventofifteen.Add(15);
eleventofifteen.Add(1);
if (fivetoeight.IsSubsetOf(onetoten))
{
Console.WriteLine("fivetoeight is subset of onetoten.");
}
if (fivetoeight.IsSupersetOf(fivetoeight))
{
Console.WriteLine("ontoten is superset of fivetoten");
}
/* OUT PUT
fivetoeight is subset of onetoten.
ontoten is superset of fivetoten
*/
onetoten.UnionWith(eleventofifteen);//这里包含重复的元素
Console.WriteLine("unio");
foreach (int tmp in onetoten)
{
Console.WriteLine(tmp);
}
onetoten.IntersectWith(fivetoeight);
Console.WriteLine("intersect");
foreach (int tmp in onetoten)
{
Console.WriteLine(tmp);
}
Console.WriteLine("except");
onetoten.ExceptWith(fivetoeight);
foreach (int tmp in onetoten)
{
Console.WriteLine(tmp);
}
/*OUT PUT: first execute the union operation,
* second execute the intersection operation using last result,
* third execute the exception operation using last result.
*
unio
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
intersect
5
6
7
8
except
*
*
*/
}
IDictionary
namespace System.Collections.Generic
{
public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
{
ICollection<TKey> Keys { get; }
ICollection<TValue> Values { get; }
TValue this[TKey key] { get; set; }
void Add(TKey key, TValue value);
bool ContainsKey(TKey key);
bool Remove(TKey key);
bool TryGetValue(TKey key, out TValue value);
}
}
public static void DictionaryTest()
{
Dictionary<string, string> programBook = new Dictionary<string, string>();
programBook.Add("chapter1", "base programming skill");
programBook.Add("chapter2", "the amateurism programming skill");
programBook.Add("chapter3", "the professional programming skill");
programBook.Add("chapter4", "the god programming skill");
strDictionary = programBook as IDictionary<string, string>;
if (strDictionary != null)
{
Random rand = new Random();
string[] content = strDictionary.Keys.ToArray<string>();
Console.WriteLine(strDictionary[content[rand.Next(0, 4)]]);
}
/**OUT PUT
base programming skill
* **/
}
ILookup
namespace System.Linq
{
public interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>, IEnumerable
{
int Count { get; }
IEnumerable<TElement> this[TKey key] { get; }
bool Contains(TKey key);
}
}
public static void LookupTest()
{
Person[] persons = new Person[]{
new Person{firstName="Li",lastName="Ming",age=21},
new Person{firstName="Li",lastName="XinLiang",age=22},
new Person{firstName="Wang",lastName="Kai",age=23},
new Person{firstName="Li",lastName="SiMing",age=24}
};
var personsContent = persons.ToLookup(person => person.firstName);
ILookup<string, Person> ok = persons.ToLookup<Person, string>(a => a.firstName);
foreach (Person tmp in personsContent["Li"])
{
Console.WriteLine(tmp.firstName + tmp.lastName);
}
Console.WriteLine("*");
foreach (Person tmp in ok["Li"])
{
Console.WriteLine(tmp.firstName + tmp.lastName);
}
/*OUT PUT
LiMing
LiXinLiang
LiSiMing
*
LiMing
LiXinLiang
LiSiMing
*/
}
IComparer
namespace System.Collections.Generic
{
public interface IComparer<in T>
{
int Compare(T x, T y);
}
}
public static void IComparerTest()
{
List<Person> people = new List<Person>();
Person jim = new Person { firstName = "jim", lastName = "wang", age = 30 };
Person bank = new Person { firstName = "bank", lastName = "Li", age = 90 };
Person Lily = new Person { firstName = "Lily", lastName = "Qin", age = 38 };
people.Add(bank);
people.Add(Lily);
people.Add(jim);
Person tmp = new Person();
IComparer<Person> compararion = tmp as IComparer<Person>;
people.Sort(compararion);
foreach (Person p in people)
{
Console.WriteLine(p.firstName);
}
/*OUT PUT
jim
Lily
bank
*/
}
IEqualityComparer
用法见《常用算法帖(C#): 数组 》
namespace System.Collections.Generic
{
public interface IEqualityComparer<in T>
{
bool Equals(T x, T y);
int GetHashCode(T obj);
}
}
IGrouping
namespace System.Linq
{
public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable
{
TKey Key { get; }
}
}
public static void IGroupingTest()
{
Person[] persons = new Person[]{
new Person{firstName="Li",lastName="Ming",age=21},
new Person{firstName="Li",lastName="XinLiang",age=22},
new Person{firstName="Wang",lastName="Kai",age=23},
new Person{firstName="Li",lastName="SiMing",age=24}
};
ILookup<string, Person> ok = persons.ToLookup<Person, string>(a => a.firstName);
var iterator = ok.GetEnumerator();
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Key);
}
}
ObservableCollection
public static void ObserverCollectionTest()
{
ObservableCollection<string> paperFirm = new ObservableCollection<string>();
string[] personList = new string[] { "Bank", "Bruce" };
paperFirm.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(paperFirm_CollectionChanged);
paperFirm.Add("Jim");
paperFirm.Add("Lucy");
paperFirm.Add("Alex");
paperFirm.Add("Jeff");
paperFirm.Remove("Jim");//删除jim
paperFirm.Remove("Lucy");//删除lucy
paperFirm.Clear();//这个事件会触发 Reset事件
/*OUT PUT
you add a element in 0,it is value is Jim
you add a element in 1,it is value is Lucy
you add a element in 2,it is value is Alex
you add a element in 3,it is value is Jeff
you remove a element in 0,it is value is Jim
you remove a element in 0,it is value is Lucy
reset event!
*/
}
static void paperFirm_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
Console.WriteLine(string.Format("you add a element in {0},it is value is {1}", new object[] { e.NewStartingIndex, ((ObservableCollection<string>)sender)[e.NewStartingIndex] }));
}
if (e.Action == NotifyCollectionChangedAction.Remove)
{
Console.WriteLine(string.Format("you remove a element in {0},it is value is {1}", new object[] { e.OldStartingIndex, e.OldItems[0] }));
}
if (e.Action == NotifyCollectionChangedAction.Replace)
{
}
if (e.Action == NotifyCollectionChangedAction.Reset)
{
Console.WriteLine("reset event!");
}
}
LinkedTable
public static void LinkedTable()
{
LinkedList<string> address = new LinkedList<string>();
LinkedListNode<string> jim = new LinkedListNode<string>("Jim");
LinkedListNode<string> bob = new LinkedListNode<string>("bob");
LinkedListNode<string> clark = new LinkedListNode<string>("clark");
LinkedListNode<string> ben = new LinkedListNode<string>("ben");
address.AddFirst(jim);
address.AddAfter(jim, bob);
address.AddAfter(bob, clark);
address.AddAfter(clark, ben);
int offset = 1;
LinkedListNode<string> current=address.First;
do
{
Console.WriteLine(current.Value);
current = current.Next;
offset++;
} while (offset<=address.Count);
}