首页 > 代码库 > Linq的简单实用
Linq的简单实用
很少用linq,所以写点基本的用法,学习一下,先介绍下使用的两个类(偷懒在网上找了一个Ticket类);
public class User { public int UserID { get; set; } public string UserName { get; set; } public static List<User> GetList() { return new List<User>() { new User() { UserID=1,UserName="James"}, new User() { UserID=2,UserName="Wade"}, new User() { UserID=3,UserName="Paul"}, new User() { UserID=4,UserName="Curry"}, new User() { UserID=5,UserName="Ivan"} }; } }
public class Ticket { /// <summary> /// 票号 /// </summary> public string TicketNo { get; set; } /// <summary> /// 订单号 /// </summary> public int OrderID { get; set; } /// <summary> /// 备注 /// </summary> public string Description { get; set; } public int UserID { get; set; } public static List<Ticket> GetList() { return new List<Ticket>() { new Ticket(){ TicketNo="999-12311",OrderID=79121281,Description="改签",UserID=1}, new Ticket(){ TicketNo="999-24572",OrderID=29321289,Description="退票",UserID=2}, new Ticket(){ TicketNo="999-68904",OrderID=19321289,Description="成交",UserID=3}, new Ticket(){ TicketNo="999-24172",OrderID=64321212,Description="未使用",UserID=4}, new Ticket(){ TicketNo="999-24579",OrderID=19321289,Description="退票",UserID=5}, new Ticket(){ TicketNo="999-21522",OrderID=79121281,Description="未使用",UserID=1}, new Ticket(){ TicketNo="999-24902",OrderID=79121281,Description="退票",UserID=2}, new Ticket(){ TicketNo="999-04571",OrderID=29321289,Description="改签",UserID=5}, new Ticket(){ TicketNo="999-23572",OrderID=96576289,Description="改签",UserID=2}, new Ticket(){ TicketNo="999-24971",OrderID=99321289,Description="成交",UserID=5} }; } }
接下来就是关于linq的实用了
static void Main(string[] args) { var Userlist = User.GetList(); var Ticketlist = Ticket.GetList(); var list1 = from a in Userlist orderby a.UserID descending select a; var list2= from a in Userlist where a.UserID==1 select a; //左联 var list3 = from user in Userlist join ticekt in Ticketlist on user.UserID equals ticekt.UserID into temp from ticekt in temp.DefaultIfEmpty() select new { UserName = user.UserName, TicketNo = ticekt!=null?ticekt.TicketNo:null }; //右联 var list4=from user in Userlist join ticekt in Ticketlist on user.UserID equals ticekt.UserID into temp from ticekt in temp.DefaultIfEmpty() select new { UserName =user!=null? user.UserName:null, TicketNo = ticekt.Description }; //内联 var list5 = from user in Userlist join ticekt in Ticketlist on user.UserID equals ticekt.UserID select user; //group by var list6 = from ticekt in Ticketlist group ticekt by ticekt.UserID into g select new { g.Key, Count = g.Count() }; Console.Read(); }
Linq的简单实用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。