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=&quot;李山&quot;,Info=&quot;学习成绩一般&quot;,Grade=&quot;1年级&quot;}, 16: new Student{Id=123,Name=&quot;李四&quot;,Info=&quot;学习成绩良好&quot;,Grade=&quot;2年级&quot;}, 17: new Student{Id=12345,Name=&quot;李五&quot;,Info=&quot;学习成绩一般&quot;,Grade=&quot;3年级&quot;}, 18: new Student{Id=12346,Name=&quot;李六&quot;,Info=&quot;学习成绩优秀&quot;,Grade=&quot;6年级&quot;}, 19: new Student{Id=12789,Name=&quot;李七&quot;,Info=&quot;学习成绩优秀&quot;,Grade=&quot;5年级&quot;}, 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(&quot;Student{0}:{1},{2}&quot;,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 &quot;ID:&quot; + Id + &quot;Name:&quot; + Name + &quot;Info&quot; + Info + &quot;Grade&quot; + Grade; 49: } 50: 51: } 52:}
页:
[1]