zoukankan      html  css  js  c++  java
  • Lambda表达式select()和where()的区别

    可能很多同学和我一样对于select()和where()区别并不是太清晰,其实两者还是有本质区别的。

    1、where()用法:必须加条件,且返回对象结果。

       static void Main(string[] args)
       {
           

    List<Person> listPerson = new List<Person>();
    listPerson.Add(new Person { Name = "Alice", Address = "北京", Age = 30 });
    listPerson.Add(new Person { Name = "Joe", Address = "上海", Age = 34 });
    listPerson.Add(new Person { Name = "Cat", Address = "广州", Age = 24 });
    listPerson.Add(new Person { Name = "Alan", Address = "深圳", Age = 26 });
    listPerson.Add(new Person { Name = "Tom", Address = "重庆", Age = 28 });
    listPerson.Add(new Person { Name = "Jarrey", Address = "天津", Age = 40 });


    IEnumerable<Person> results = listPerson.Where(p => p.Name.Contains("a"));//必须加条件,返回对象

     foreach(var item in results )
     {
            Console.WriteLine(item.Name);
     }

          Console.WriteLine("按任意键可退出!");
          Console.ReadKey();
       }

    结果:Cat Alan Jarrey。

    Alice虽然也包含a但是是大写的A,所以输出结果是不会包含Alice。

    2、select()用法:

    (1)(a=>a.Value=="22")加条件查询时,返回bool型结果;

    (2)(a=>a)没条件返回对象

    (1)(a=>a.Value=="22")加条件查询时,返回bool型结果

    static void Main(string[] args)
    {
        string[] arrays={"asd","abc","bbb","ccc"};
        var results = arrays.Select(a => a.Contains("b"));//加条件查询时,返回bool型结果

        foreach(var da in results )
        {
             Console.WriteLine(da);
        }

       Console.WriteLine("按任意键可退出!");
       Console.ReadKey();
    }

    结果:False  True  True  False

    (2)(a=>a)没条件返回对象

    static void Main(string[] args)
    {
        string[] arrays={"12","13","14","15"};
        var results = arrays.Select(a => a);//没条件,返回所有对象;

        foreach(var da in results ) 
       {
            Console.WriteLine(da);
       }

       Console.WriteLine("按任意键可退出!");
       Console.ReadKey();
    }

    结果:12 13 14 15

  • 相关阅读:
    正则表达式点滴
    异步处理与界面交互
    关于利用VS2008创建项目遇到的小困惑备忘
    using App.cofig to Store value
    Castle ActiveRecord学习笔记三:初始化配置
    无服务器端的UDP群聊功能剖析
    为VS2010默认模板添加版权信息
    理论有何用?不问“何用”,先问“用否”!
    微软没有公开的游标分页
    那些满脑子只考虑后台数据库的人他整天研究的就是针对自己查询一些数据的sql语句
  • 原文地址:https://www.cnblogs.com/become/p/8669745.html
Copyright © 2011-2022 走看看