Student[] stAry ={ new Student("张三","男",18), new Student("小明","男",18), new Student("丽丽","女",18), new Student("小菊","女",18), new Student("张四","男",18), new Student("张八","男",18), }; var query1 = from vall in stAry select vall; foreach (Student st in query1) System.Console.WriteLine(st); var query2 = from val2 in stAry select val2.Age; foreach (var age in query2) { System.Console.WriteLine("{0}",age); } var query3 = from val2 in stAry select val2.Name.Length ; foreach (var name in query3) { System.Console.WriteLine(name); }
where 的用法:
int[] ary = { 1, 3, 9, 12, 34, 12, 25, 33, 67, 45, 78 }; var query1 = from val1 in ary where val1 > 15 select val1; foreach (var val in query1) System.Console.WriteLine(val);
orderby的用法:
Student [] stary= { new Student ("王小二","男",17), new Student ("张武率军","男",22), new Student ("徐暾于灏","男",22), new Student ("一朵鲜花","女",18), }; var query1 = from val1 in stary orderby val1.Age select val1; foreach (var st in query1) { System.Console.WriteLine("{0}--{1}--{2}", st.Name, st.XingBie, st.Age); }
默认为升序,ascending,可以设置为降序 desending。
可以指定多个关键字
如果同一个查询中出现多个orderby,则只有最后一个有效。与where的取并集的效果不同。
用group 分组:
var query1 = from st in stary group st by st.XingBie; foreach (var grp in query1) { System.Console.WriteLine(grp.Key); foreach(var stu in grp) { System.Console.WriteLine(stu); } } var query2 = from st in stary group st by st.Age into stgrp_age select stgrp_age; foreach(var age in query2) { System.Console.WriteLine(age.Key + ":"); foreach(var stu in age) { System.Console.WriteLine(stu); } }
时间: 2024-12-29 11:09:14