最近比较喜欢LINQ,真是碉堡了。下面写了个例子演示一下LINQ对List<T>的操作,包括排序、where条件、选部分数据等查询。最近偷懒,不写注释了,大家自己看一下就明白了~
测试用的BLL和Model
03 |
public List<TestModel> GetList() |
05 |
return new List<TestModel>() |
07 |
new TestModel(){ Id=1, Name= "RYWE" , Content= "IOJADJ" , Posttime=DateTime.Now.AddHours(1) }, |
08 |
new TestModel(){ Id=2, Name= "JGFA" , Content= "CAFYRE" , Posttime=DateTime.Now.AddHours(0) }, |
09 |
new TestModel(){ Id=4, Name= "PIOU" , Content= "OVXZLA" , Posttime=DateTime.Now.AddHours(5) }, |
10 |
new TestModel(){ Id=5, Name= "OUIH" , Content= "AIPJLM" , Posttime=DateTime.Now.AddHours(3) }, |
11 |
new TestModel(){ Id=7, Name= "ZCXI" , Content= "KUQOPA" , Posttime=DateTime.Now.AddHours(7) } |
16 |
public class TestModel |
18 |
public int Id { get ; set ; } |
19 |
public string Name { get ; set ; } |
20 |
public string Content { get ; set ; } |
21 |
public DateTime Posttime { get ; set ; } |
27 |
public override string ToString() |
29 |
StringBuilder sb = new StringBuilder(); |
30 |
sb.Append(String.Format( "{0}={1}, " , "Id" , this .Id)); |
31 |
sb.Append(String.Format( "{0}={1}, " , "Name" , this .Name)); |
32 |
sb.Append(String.Format( "{0}={1}, " , "Content" , this .Content)); |
33 |
sb.Append(String.Format( "{0}={1}" , "Posttime" , this .Posttime)); |
测试代码:
01 |
static void Main( string [] args) |
04 |
TestBLL bll = new TestBLL(); |
05 |
List<TestModel> mList = bll.GetList(); |
07 |
var query = from m in mList |
10 |
var query1 = from m in mList |
14 |
var query2 = from m in mList |
16 |
orderby m.Id descending |
19 |
var query3 = from m in mList |
20 |
orderby m.Posttime descending |
23 |
var query4 = (from m in mList |
26 |
var query5 = from m in mList |
27 |
orderby m.Name ascending |
30 |
PrintList( "from m in mList select m" , query); |
31 |
PrintList( "from m in mList where m.Id > 2 select m" , query1); |
32 |
PrintList( "from m in mList select m" , query2); |
33 |
PrintList( "from m in mList orderby m.Posttime descending select m" , query3); |
34 |
PrintList( "(from m in mList where select m).Take(3)" , query4); |
35 |
PrintList( "from m in mList orderby m.Name ascending select m" , query5); |
41 |
private static void PrintList( string expression, IEnumerable<TestModel> query) |
43 |
Console.WriteLine( "Query expression: " + expression); |
44 |
Console.WriteLine( "__________________________________________________________________" ); |
45 |
foreach (var item in query) |
47 |
Console.WriteLine(item.ToString()); |
49 |
Console.WriteLine( "\n" ); |
有图有真相:
本文系转载,具体哪的 问百度吧 我找快照看的