LINQ to List泛型的几种简单查询
最近比较喜欢LINQ,真是碉堡了。下面写了个例子演示一下LINQ对List<T>的操作,包括排序、where条件、选部分数据等查询。最近偷懒,不写注释了,大家自己看一下就明白了~
测试用的BLL和Model
public class TestBLL { public List<TestModel> GetList() { return new List<TestModel>() { new TestModel(){ Id=1, Name="RYWE", Content="IOJADJ", Posttime=DateTime.Now.AddHours(1) }, new TestModel(){ Id=2, Name="JGFA", Content="CAFYRE", Posttime=DateTime.Now.AddHours(0) }, new TestModel(){ Id=4, Name="PIOU", Content="OVXZLA", Posttime=DateTime.Now.AddHours(5) }, new TestModel(){ Id=5, Name="OUIH", Content="AIPJLM", Posttime=DateTime.Now.AddHours(3) }, new TestModel(){ Id=7, Name="ZCXI", Content="KUQOPA", Posttime=DateTime.Now.AddHours(7) } }; } } public class TestModel { public int Id { get; set; } public string Name { get; set; } public string Content { get; set; } public DateTime Posttime { get; set; } public TestModel() { } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(String.Format("{0}={1}, ", "Id", this.Id)); sb.Append(String.Format("{0}={1}, ", "Name", this.Name)); sb.Append(String.Format("{0}={1}, ", "Content", this.Content)); sb.Append(String.Format("{0}={1}", "Posttime", this.Posttime)); return sb.ToString(); } }
测试代码:
static void Main(string[] args) { TestBLL bll = new TestBLL(); List<TestModel> mList = bll.GetList(); var query = from m in mList select m; var query1 = from m in mList where m.Id > 2 select m; var query2 = from m in mList where m.Id > 2 orderby m.Id descending select m; var query3 = from m in mList orderby m.Posttime descending select m; var query4 = (from m in mList select m).Take(3); var query5 = from m in mList orderby m.Name ascending select m; PrintList("from m in mList select m", query); PrintList("from m in mList where m.Id > 2 select m", query1); PrintList("from m in mList select m", query2); PrintList("from m in mList orderby m.Posttime descending select m", query3); PrintList("(from m in mList where select m).Take(3)", query4); PrintList("from m in mList orderby m.Name ascending select m", query5); Console.ReadKey(); } private static void PrintList(string expression, IEnumerable<TestModel> query) { Console.WriteLine("Query expression: " + expression); Console.WriteLine("__________________________________________________________________"); foreach (var item in query) { Console.WriteLine(item.ToString()); } Console.WriteLine("\n"); }
有图有真相: