List的使用
List<T>类表示可通过索引访问的对象的强类型列表,提供用于对列表进行搜索、排序和操作的方法。(实例化对象可通过索引访问。列表,通过索引访问列表数据。)
泛型最常见的用途是泛型集合
我们在创建列表类时,列表项的数据类型可能是int,string或其它类型,如果对列表类的处理方法相同,就没有必要事先指定数据类型,留待列表类实例化时再指定。相当于把数据类型当成参数,这样可以最大限度地重用代码,保护类型的安全以及提高性能。
List的一般用法
所属命名空间: System.Collections.Generic
public class List<T>:IList<T>,Icollection<T>,IEnumerable<T>,IList,Icollection,Ienumerable List<T>是ArrayList类的泛型等效类,该类使用大小可按需动态增加的数组实现IList<T>泛型接口
(1)声明 List<T>mlist = new List<T>();
string[] Arr = { "a", "b", "c" };
List<string> mlist = new List<string>(Arr);
for (int i = 0; i < mlist.Count; i++) {
Console.WriteLine(mlist[i]);
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string[] Arr = { "a", "b", "c" }; List<string> mlist = new List<string>(Arr); mlist.Add("d");//添加一个元素 //添加集合 string[] Arr2 ={"f","g","h"}; mlist.AddRange(Arr2); //在index位置添加一个元素 Insert(int index,T item) mlist.Insert(1, "p"); //遍历List中元素 for (int i = 0; i < mlist.Count; i++) { Console.WriteLine(mlist[i]); } //List.Remove(T item) 删除一个值 mlist.Remove("a"); //List.RemoveAt(int index);删除下标为index的元素 mlist.RemoveAt(0); //List.RemoveRange(int index,int count); 下标index开始,删除count个元素 mlist.RemoveRange(3, 2); //判断某个元素是否在该List中 //List.Contains(T item) 返回true或false if (mlist.Contains("g")) { Console.WriteLine("g存在列表中"); } else { mlist.Add("g"); } //给List里面元素排序 List.Sort() 默认是元素每一个字母按升序 mlist.Sort(); //给List里面元素顺序反转 List.Reverse() 可以与List.Sort()配合使用 //List清空 List.Clear() mlist.Clear(); //获得List中元素数目 List.Count() 返回int值 mlist.Count(); foreach (string element in mlist) //T的类型与mlist声明时一样 { Console.WriteLine(element); } } } }
public List<t_a_member_type> GetAllMemberTypes() { return vContext.t_a_member_type.ToList(); }
public ActionResult CustSalesmanQuery() { //客户类型 MemberTypeBLL membll = new MemberTypeBLL(); List<t_a_member_type> list = membll.GetAllMemberTypes(); list.Insert(0, new t_a_member_type { type = 0, table_name = "请选择" }); ViewData["typelist"] = new SelectList(list, "type", "type_name", "");//用户类型select //客服人员 List<t_a_member> lsMember = ub.GetSalesman(); lsMember.Insert(0, new t_a_member { id = 0, name = "请选择" }); ViewData["salesmanlist"] = new SelectList(lsMember, "id", "name", ""); return View(); }
客户类型:<%: Html.DropDownList("ddltype", ViewData["typelist"] as SelectList)%>