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.


转载于:https://www.cnblogs.com/bfy-19/archive/2012/08/01/2617908.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值