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

原文地址:https://www.cnblogs.com/become/p/8669745.html