- using System;
- using System.Collections.Generic;
- public partial class List : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- CreateList();
- }
- private void CreateList()
- {
- List<string> list = new List<string>();
- list.Add("Compsognathus");
- list.Add("Amargasaurus");
- list.Add("Oviraptor");
- list.Add("Velociraptor");
- list.Add("Deinonychus");
- list.Add("Dilophosaurus");
- list.Add("Gallimimus");
- list.Add("Triceratops");
- //循環輸出每一項
- Response.Write("分別輸出每一項:");
- foreach (string str in list)
- {
- Response.Write(str + ";");
- }
- //查找字符串中包含saurus的字符,利用了匿名方法(第一種方式)
- List<string> listFind = list.FindAll(delegate(string s){
- return s.Contains("saurus");
- });
- Response.Write("查找到的字符串為:");
- foreach (string str in listFind)
- {
- Response.Write(str+" ;");
- }
- //第二種方式,這兩種方式實際上是等價的
- Response.Write("</br>FindAll(EndWithSaurus):");
- List<string> subList = list.FindAll(EndWithSaurus);//傳入了一個方法名
- foreach (string str in subList)
- {
- Response.Write(str+" ;");
- }
- }
- private bool EndWithSaurus(string s)
- {
- if ((s.Length > 5) && (s.Substring(s.Length - 6).ToLower() == "saurus"))
- return true;
- else
- return false;
- }
- }
過濾條件用法
List<string> subList = list.FindAll(delegate(itemType x){return x.id==i;});
就可以了。其中itemType是你的元素的類型,即List <T> 中的類型參數T。