LinQ综合应用实例
直接上代码,内容很浅显易懂,在这里就不做更多的解释,解释见代码注释。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Threading.Tasks; public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string[] names = { "Wang", "Biao", "WangBiao", "Kingtiger" }; var q1 = names.Where(a => a.StartsWith("W"));//直接查询 var q2 = from a in names where a.StartsWith("W") select a;//linq查询 var q3 = from a in names where a.StartsWith("W") orderby a descending select a;//linq查询,包括排序,倒序要加上descending var q4 = names.OrderBy(a => a).Where(a=>a.StartsWith("W"));//直接排序 var q5 = names.OrderByDescending(a => a).Where(a=>a.StartsWith("W"));//直接倒序排序 var q6 = from a in names select new { HI = a + ",您好!" };//查询后重构输出 var q7 = names.Select(a => new { HI = a + ",您好!" });//直接查询构造输出 List<Person> persons = new List<Person>(); persons.Add(new Person() { ID="0001",Name="Kingtiger" }); persons.Add(new Person() { ID = "0002", Name = "Wang" }); persons.Add(new Person() { ID = "0001", Name = "Biao" }); persons.Add(new Person() { ID = "0004", Name = "WangBiao" }); var q8 = from p in persons orderby p.ID, p.Name select p;//多级排序,先排序ID,然后再排序Name var q9 = persons.OrderBy(a => a.ID).ThenBy(a => a.Name).Select(a => a);//直接两个排序 var qt = from p in persons where p.Name.Contains("W") || p.Name.Contains("Biao") select p;//第一次查询进行过滤 var q10 = from p in qt orderby p.Name descending select p.Name;//对一次查询结果进行第二次处理 var q11 = from p in persons group p by p.ID into cg select new { GroupID = cg.Key, GroupCount= cg.Count() };//分组查询,将结果提取出来 List<Order> orders = new List<Order>(); orders.Add(new Order() { UserID="0002",OrderID="001", OrderName="苹果" }); orders.Add(new Order() { UserID = "0002", OrderID = "003", OrderName = "香蕉" }); orders.Add(new Order() { UserID = "0004", OrderID = "002", OrderName = "荔枝" }); var q12 = from p in persons join o in orders on p.ID equals o.UserID select new { PName = p.Name, POrderName = o.OrderName }; foreach (var p in q12) { Response.Write(p+"<br/>"); } } } public class Person { public string ID { set; get; } public string Name { set; get; } } public class Order { public string OrderID { set; get; } public string OrderName { set; get; } public string UserID { set; get; } }