List中FindAll用法的一些简单示例并与where的区别
转载:http://blog.csdn.net/luoxufeng/article/details/6925982
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; } }
2.区别:
FindAll是.net 2.0中的东西,而Where是为了linq而实现的扩展方法,是3.5中的东西
前者使用的是Predicate<T>委托,而后者却是Func<T, bool>委托。
FindAll is a method on the List<T> class, and can only be used for objects of that type. Note that it returns a List<T> too, so there' no need to call ToList on the return value.
Where is an extension method that can be used on any IEnumerable<T> sequence. So if you're writing generic code that can operate on collections other than List<T>, Where is what you'd use.