Linq——First、ElementAt、Any、all
#region using
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;
#endregion
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
#region 用First()选择查询结果的第一个元素
Response.Write("<hr>用First()选择查询结果的第一个元素<br>");
Student student = (from s in GetStudents()
where s.Language == "Chinese"
select s)
.First();
Response.Write(string.Format("<div class='result'>{0},{1},{2}</div>", student.Name, student.Age, student.Language));
#endregion
#region 用First()的Lambda表达式选择查询结果的第一个元素
Response.Write("<hr>用First()的Lambda表达式选择查询结果的第一个元素<br>");
Student student2 = GetStudents().First(s => s.Age < 20);
Response.Write(string.Format("<div class='result'>{0},{1},{2}</div>", student2.Name, student2.Age, student2.Language));
#endregion
#region 用ElementAt()选择查询结果中指定位置的元素
Response.Write("<hr>用ElementAt()选择查询结果中指定位置的元素<br>");
Student student3 = GetStudents().ElementAt(3);
Response.Write(string.Format("<div class='result'>{0},{1},{2}</div>", student3.Name, student3.Age, student3.Language));
#endregion
#region 用Any判断查询结果中是否有元素满足条件
Response.Write("<hr>用Any判断查询结果中是否有元素满足条件<br>");
bool ifany = GetStudents().Any(s=>s.Age>20);
Response.Write(ifany.ToString());
#endregion
#region 用all()判断查询结果是否所有元素都满足条件
Response.Write("<hr>用all()判断查询结果是否所有元素都满足条件<br>");
bool ifall = GetStudents().All(s => s.Age > 20);
Response.Write(ifall.ToString());
#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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。