Linq查询Count、Sum、Min、Max、Average

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;
  #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>);
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=,
Language="Chinese"
},
new Student
{
Name="JESSIE",
Age=,
Language="Scotland"
},
new Student
{
Name="KELLY",
Age=,
Language="English"
},
new Student
{
Name="JUNE",
Age=,
Language="English"
}
};
return students;
}
#endregion #region 学生类
class Student
{
public int Age { get; set; }
public string Name { get; set; }
public string Language { get; set; }
}
#endregion
上一篇:golang:interface{}类型测试


下一篇:如何从线程返回信息——轮询、回调、Callable