Linq——Count、Sum、Min、Max、Average
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Text; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; using System.Collections; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { #region 用Count()得出查询结果的个数 Response.Write("<hr>用Count()得出查询结果的个数<br>"); var langCount = (from s in GetStudents() select s.Language) .Distinct() .Count(); Response.Write(string.Format("<div class='result'>{0}</div>", langCount)); #endregion #region 用Count()的Lambda表达式满足条件的元素个数 Response.Write("<hr>用Count()得出查询结果的个数<br>"); var ageCoun = (from s in GetStudents() select s.Age) .Count(a=>a>22); Response.Write(string.Format("<div class='result'>{0}</div>", ageCoun)); #endregion #region 用Sum()将查询结果相加 Response.Write("<hr>用Sum()将查询结果相加<br>"); var ageSum = (from s in GetStudents() select s.Age) .Sum(); //var ageSum = GetStudents().Sum(s=>s.Age); Response.Write(string.Format("<div class='result'>{0}</div>", ageSum)); #endregion #region 用Min()得出查询结果的最小值 Response.Write("<hr>用Min()得出查询结果的最小值<br>"); var ageMin = (from s in GetStudents() select s.Age) .Min(); //var ageMin = GetStudents().Min(s => s.Age); Response.Write(string.Format("<div class='result'>{0}</div>", ageMin)); #endregion #region 用Max()得出查询结果的最大值 Response.Write("<hr>用Max()得出查询结果的最大值<br>"); var ageMax = (from s in GetStudents() select s.Age) .Max(); //var ageMax = GetStudents().Max(s => s.Age); Response.Write(string.Format("<div class='result'>{0}</div>", ageMax)); #endregion #region 用Average()得出查询结果的平均值 Response.Write("<hr>用Average()得出查询结果的平均值<br>"); var ageAverage = (from s in GetStudents() select s.Age) .Average(); //var ageAverage = GetStudents().Average(s => s.Age); Response.Write(string.Format("<div class='result'>{0}</div>", ageAverage)); #endregion } #region 构造一个学生集合体 private List<Student> GetStudents() { List<Student> students = new List<Student> { new Student{ Name="YOUNG", Age=25, Language="Chinese"}, new Student{ Name="JESSIE", Age=21, Language="Scotland"}, new Student{ Name="KELLY", Age=18, Language="English"}, new Student{ Name="JUNE", Age=20, Language="English"}, new Student{ Name="ADRIAN", Age=22, Language="Italy"}, new Student{ Name="BRUCE", Age=17, Language="Scotland"}, new Student{ Name="BRANT", Age=30, Language="Germany"}, new Student{ Name="BEN", Age=25, Language="Chinese"} }; return students; } #endregion } #region 学生类 class Student { public int Age { get; set; } public string Name { get; set; } public string Language { get; set; } } #endregion
转自:http://blog.sina.com.cn/s/blog_5421dfd20100i6cw.html