奇异果Kiwi 发表于 2013-1-2 23:11:17

LinQ学习笔记(二)

<div id="cnblogs_post_body">前言                    

   
        学习了数组的查询之后。前面就知道了Linq数据源必须是是可枚举的——即必须是数组和集合以便从中选择一个。所以接下学习的就是集合了。集合里面最常见的就是对象了,那么我们就针对对象查询,也是项目中很常用的。
 


正文            

    1.查询的是对象
   那么首先建立对象,再对其进行查询

<div class="csharpcode">      1:using System;   2:using System.Collections.Generic;   3:using System.Linq;   4:using System.Text;   5:using System.Threading.Tasks;   6:using System.IO;   7:    8:namespace ConsoleApplication1   9:{    10:      class LinqTest2    11:      {    12:          static void Main(string[] args)    13:          {    14:            List<Student> students = new List<Student> {   15:            new Student{Id=123,Name="李山",Info="学习成绩一般",Grade="1年级"},    16:            new Student{Id=123,Name="李四",Info="学习成绩良好",Grade="2年级"},    17:            new Student{Id=12345,Name="李五",Info="学习成绩一般",Grade="3年级"},    18:            new Student{Id=12346,Name="李六",Info="学习成绩优秀",Grade="6年级"},   19:            new Student{Id=12789,Name="李七",Info="学习成绩优秀",Grade="5年级"},    20:     21:            };    22:          /////////////////////////////////////////////////////////    23:          //第一种原始的查询方法。很像sql查询语句,只不过这里用的是对象    24:          var queryResults= from c in students    25:                            where c.Id==123    26:                            select c//此处是查询整个对象    27:                              ;    28:          foreach(Student s in queryResults)    29:          {    30:            Console.WriteLine(s);//这里输出的是c默认调用其ToString()的方法,不复写这输出类名    31:            //Console.WriteLine("Student{0}:{1},{2}",s.Id,s.Name,s.Info);    32:          }    33:          /////////////////////////////////////////////////////////    34:            Console.ReadKey();    35:          }    36:      }    37:      class Student   38:      {    39:     40:          public int Id { get; set; }    41:          public string Name { get; set; }    42:          public string Info { get; set; }    43:          public string Grade { get; set; }    44:     45:          public override string ToString()    46:          {    47:     48:            return "ID:" + Id + "Name:" + Name + "Info" + Info + "Grade" + Grade;    49:          }    50:     51:      }    52:}
页: [1]
查看完整版本: LinQ学习笔记(二)