C#中的List怎么样?List<T>类是ArrayList类的泛型等效类,该类使用大小可按需动态增加的数组实现IList<T>泛型接口。接下来,小编就介绍一些List的基础简单用法。 泛型的好处:它为使用c#语言编写面向对象程序增加了极大的效力和灵活性。不会强行对值类型进行装箱和拆箱,或对引用类型进行向下强制类型转换,所以性能得到提高。 性能注意事项:在决定使用IList<T>还是使用ArrayList类(两者具有类似的功能)时,记住IList<T>类在大多数情况下执行得更好并且是类型安全的。如果对IList<T>类的类型T 使用引用类型,则两个类的行为是完全相同的。但是,如果对类型T 使用值类型,则需要考虑实现和装箱问题。 C# List的基础常用方法: 一、声明: 1、List<T> mList = new List<T>(); T为列表中元素类型,现在以string类型作为例子: List<string> mList = new List<string>(); 2、List<T> testList =new List<T> (IEnumerable<T> collection); 以一个集合作为参数创建List: string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu"}; List<string> testList = new List<string>(temArr); 二、添加元素: 1、List. Add(T item)添加一个元素 例: mList.Add("John"); 2、List. AddRange(IEnumerable<T> collection)添加一组元素 例: string[] temArr = {"Ha","Hunter","Tom","Lily","Jay","Jim","Kuku","Locu"};mList.AddRange(temArr); 3、Insert(intindex, T item);在index位置添加一个元素 例: mList.Insert(1,"Hei"); 三、遍历List中元素: foreach(TelementinmList)T的类型与mList声明时一样 { Console.WriteLine(element); } 例: foreach(stringsinmList) { Console.WriteLine(s); } 四、删除元素: 1、List. Remove(T item)删除一个值 例: mList.Remove("Hunter"); 2、List. RemoveAt(intindex);删除下标为index的元素 例: mList.RemoveAt(0); 3、List. RemoveRange(intindex,intcount); 从下标index开始,删除count个元素 例: mList.RemoveRange(3, 2); 五、判断某个元素是否在该List中: List. Contains(T item)返回true或false,很实用 例: if(mList.Contains("Hunter")) { Console.WriteLine("There is Hunter in the list"); } else { mList.Add("Hunter"); Console.WriteLine("Add Hunter successfully."); } 六、给List里面元素排序: List. Sort ()默认是元素第一个字母按升序 例: mList.Sort(); 七、给List里面元素顺序反转: List. Reverse ()可以不List. Sort ()配合使用,达到想要的效果 例: mList.Sort(); 八、List清空: List. Clear () 例: mList.Clear(); 九、获得List中元素数目: List. Count ()返回int值 例: in tcount = mList.Count(); Console.WriteLine("The num of elements in the list: "+count); |
|
来自: 昵称11881224 > 《电脑系统》