Linq基础学习(二)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {          
            List<User> user = new List<User>();
            user.Add(new User() { UserId = 00001, Name = "孔军", City = "河南" });
            user.Add(new User() { UserId = 00002, Name = "张五", City = "山西" });
            user.Add(new User() { UserId = 00003, Name = "王二", City = "河南" });

            List<Login> login = new List<Login>();
            login.Add(new Login() { UserId = 00001, Password = "123456" });
            login.Add(new Login() { UserId = 00002, Password = "000000" }); 
            login.Add(new Login() { UserId = 00003, Password = "111111" });

            var queryCustomers = from c in user
                                 group c by c.City;   //查询User里数据,以City为组
            foreach (var jg in queryCustomers)
            {
                Console.WriteLine(jg.Key);     //输出组
                foreach (var c in jg)
                {
                    Console.WriteLine("  {0},{1}", c.Name, c.UserId);  //输出组内内容
                }
            }

            var queryJoin = from c in user
                            join e in login on c.UserId equals e.UserId
                            select new {UserId = c.UserId,UserPwd=e.Password,UserName=c.Name,UserCity=c.City   };
                    //使用join连接两个表查询,查询字段UserId,查询结果定义为一个新表,
                    // 将查询结果输出
            foreach (var p in queryJoin)
            {
                Console.WriteLine("{0} {1} {2} {3}", p.UserId,p.UserPwd, p.UserName, p.UserCity);           
            }
            Console.ReadKey();
        }
    }
    class User  //用户类
    {
        public int UserId { set; get; }
        public string Name{ set;get;}
        public string City { set; get; }
    }
    class Login  //登陆类
    {
        public int UserId { set; get; }
        public string Password { set; get; }
    }

}

linq基础

posted on 2015-10-28 15:56  恋不恋  阅读(125)  评论(0)    收藏  举报

导航