您的位置:首页 > 编程语言 > C#

C#2.0 常用集合

2007-08-01 23:58 239 查看
集合

1.种类
一般比较常见的集合(我一般会用到的)
List<T>、Hashtable、SortedList<TKey, TValue>、Queue<T>、Stack<T>
这些集合都会继承这么几个接口
IEnumerable、ICollection、IDictionary、IList它们的层级关系如图:



继承了IEnumerable的类都可以使用Foreach语句

static void ShowArray(IEnumerable<Person> persons)
{
foreach (Person person in persons)
Console.WriteLine("Persons/tname: {1} age: {2}", person.Name, person.Age);
}

2.集合的排序
集合的排序

List<Person> list = new List<Person>();
InitArray(list);
list.Sort();

Sort有几个重载其中一个是public void Sort(IComparer<T> comparer);

也就是说如果传入一个IComparer<T>就可以规定排序的方法了




/**//// <summary>


/// 从名字到年龄进行比较


/// </summary>


class Sort : IComparer<Person>






{




IComparer

成员#region IComparer<Person> 成员


public int Compare(Person x, Person y)






{


if (x == null)






{


if (y == null)






{


// 都为空表示值相等


return 0;


}


else






{


// 如果y有值 则x<y


return -1;


}


}


else






{


if (y == null)






{


// 如果y为空 则x>y


return 1;


}


else






{


int lengthResult = x.Name.Length.CompareTo(y.Name.Length);


if (lengthResult == 0)






{


// 再从年龄开始比较


int ageResult = x.Name.CompareTo(y.Name);


if (ageResult == 0)






{


// 如果年龄相等在坐姓名比较


return x.Age.CompareTo(y.Age);


}


else






{


return ageResult;


}


}


else






{


return lengthResult;


}


}


}


}


#endregion


}




list.Sort(new Sort());



而public void Sort()是根据集合成员类中的CompareTo()方法进行比较
这个成员类必须从IComparable接口中继承


public class Person : IComparable<Person>






{


public string Name;


public int Age;


public Person(string name, int age)






{


this.Name = name;


this.Age = age;


}




IComparable

成员#region IComparable<Person> 成员




/**//// <summary>


/// 实现 IComparable 接口中的比较大小的方法


/// </summary>


/// <param name="other"></param>


/// <returns></returns>


public int CompareTo(Person other)






{


Person Person = other;


if (Person == null)


throw new Exception("The method or operation is not implemented.");


// 先从年龄开始比较


int ageResult = this.age.CompareTo(Person.age);


if (ageResult == 0)






{


// 如果年龄相等在坐姓名比较


return this.name.CompareTo(Person.name);


}


else






{


return ageResult;


}


}


#endregion


}



根据自定义的方法进行排序在某些情况下是经常使用到的

3.字典集合

// Hashtable 太常见了,不过,它不支持排序
Hashtable hashtable = new Hashtable();
// 可排序的字典
SortedList<string, Person> sortedlist = new SortedList<string, Person>();

4.Queue<T>和Stack<T>

Queue<T>利用Enqueue(T)方法加插入对象,用Dequeue(T)方式取对象
Stack<T>利用Push(T)方法插入对象,用Pop(T)方式取对象
这两个集合都有Peek()方法,都是查看最前(外)面的对象
Queue是先进先出的读取方式,Stack是先进后出的读取方式
不过,这两个都是继承IEnumerable接口,所以自然可以使用Foreach查看

代码下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: