C#常用容器总结---------List<类型>
List<类型> (相当于C++中的 vector<类型>)
1.创建 List<>
List< 类型> 名字 = new List< 类型> ( ) ;
List< int > nums = new List< int > ( ) ;
2.添加元素
List. Add ( element) ;
List< string > mList = new List< string > ( ) ;
mList. Add ( "John" ) ;
List. AddRange ( a group of element)
List< string > mList = new List< string > ( ) ;
string [ ] temArr = { "Ha" , "Hunter" , "Tom" , "Lily" , "Jay" , "Jim" , "Kuku" , "Locu" } ;
mList. AddRange ( temArr) ;
List. Insert ( index, element) ;
List< string > mList = new List< string > ( ) ;
mList. Insert ( 2 , "Hei" ) ;
遍历元素 可以用for()+index 也可以用foreach()
foreach ( T element in mList)
{
Console. WriteLine ( element) ;
}
3.删除元素
List. Remove ( element)
mList. Remove ( "Hunter" ) ;
List. RemoveAt ( index) ;
mList. RemoveAt ( 0 ) ;
List. RemoveRange ( index, count) ;
mList. RemoveRange ( 3 , 2 ) ;
4.查找元素
List. Contains ( element) ;
if ( mList. Contains ( "Hunter" ) )
{
Console. WriteLine ( "There is Hunter in the list" ) ;
}
else
{
mList. Add ( "Hunter" ) ;
Console. WriteLine ( "Add Hunter successfully." ) ;
}
5.排序
List. Sort ( ) ;
List. Sort ( ) ;
List. Reverse ( ) ;
6.清空List
List. Clear ( ) ;
7.获得List中元素的数量
List. Count ( ) ;
int count = mList. Count ( ) ;
Console. WriteLine ( "The num of elements in the list: " + count) ;