C# List中FindAll用法的一些简单示例
本文导语: 如下所示: 代码如下: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 list = ne...
如下所示:
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 list = new List();
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 listFind = list.FindAll(delegate(string s){
return s.Contains("saurus");
});
Response.Write("查找到的字符串为:");
foreach (string str in listFind)
{
Response.Write(str+" ;");
}
//第二种方式,这两种方式实际上是等价的
Response.Write("FindAll(EndWithSaurus):");
List 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;
}
}