直接上代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
/// <summary>
/// 只作为快速的测试,没考虑编码规范的问题
/// </summary>
class Program
{
static void Main(string[] args)
{
List<Student> student_List = new List<Student>();
for (int i = 0; i <= 3;i++ )
{
Student studen = new Student();
studen.Age = i + 20;
studen.Name = (i + 1).ToString();
student_List.Add(studen);
}
//查询,本人曾经出错的地方
//Student test = (Student)(from r in student_List where r.Age == 21 select r);//错误的写法,因为linq返回的是IEnumerable的 不能强制转换。
//正确的写法
var tmp = (from r in student_List where r.Age == 21 select r);
Student test = tmp.FirstOrDefault();//或者这样写Student test = tmp.First();
//查询多条
List<Student> tmp_List = (from r in student_List where r.Age >= 20 select r).ToList();
}
}
class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
}
由于做项目过程中经常需要根据ID编号来查找某一项内容,使用Linq显得就比较方便。
原文:http://www.cnblogs.com/dghwey/p/5090778.html