首页 > 代码库 > LinqToSql初探

LinqToSql初探

LINQ TO SQL是一种轻量级的ORM框架,它对ADO.NET进行了轻量级的封装,讲数据库原封不动的映射成模型,常用于中小型项目,优点:简单。缺点:数据库模型过于复杂时,可能不满足开发要求。

 

LINQ语句:

简单类型查询(string):

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace LINQ{    class Program    {        public  delegate int[] generateLotsOfNumbers(int count);//产生大量随机数        static void Main(string[] args)        {            string[] names ={"Alonso","Zheng","Smith","Jones","Smythe","Small","Ruiz","Hsieh","Jorgenson",                               "Ilyich","Singh","Samba","Fatimah"};            var queryResult1 = from n in names select n;//遍历操作            var queryResult2 = names;//lambda表达式,功能同1            var queryResult3 = from n in names where n.StartsWith("S") select n;//查询以S开头            var queryResult4 = names.Where(n => n.StartsWith("S"));// lambda表达式,功能同3            var queryResult5 = from n in names where n.StartsWith("S") orderby n select n;//升序            var queryResult6 = from n in names where n.StartsWith("S") orderby n descending select n;//降序            var queryResult7 = names.OrderBy(n => n).Where(n => n.StartsWith("S"));//lambda表达式,功能同4            var queryResult8 = names.OrderByDescending(n => n).Where(n => n.StartsWith("S"));//功能同5            //查询大型数据集            generateLotsOfNumbers ge = delegate(int count) //匿名函数            {                Random generator = new Random(0);                int[] result = new int[count];                for(int i=0;i<count;i++)                {                    result[i] = generator.Next();                }                return result;            };            int[] numbers = ge(12345678);            var queryResult9 = from n in numbers where n < 1000 select n;//条件查找            var queryResult10 = numbers.Where(n => n < 1000);//lambda表达式,功能同9            //聚合运算符            Console.WriteLine(queryResult9.Count());//数量            Console.WriteLine(queryResult9.Min());            Console.WriteLine(queryResult9.Max());            Console.WriteLine(queryResult9.Average());            Console.WriteLine(queryResult9.Sum());        }    }}

 

复杂类型查询:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace LINQ{    class Customer    {        public string ID { get; set; }        public string City { get; set; }        public string Country { get; set; }        public string Region { get; set; }        public decimal Sales { get; set; }        public override string ToString()        {            return "ID: " + ID + " City: " + City + " Country: " + Country + " Region: " + Region + " Sales: " + Sales;        }    }    class Program    {        public static void Main(string[] args)        {            List<Customer> customers = new List<Customer> {              new Customer { ID="A", City="New York", Country="USA", Region="North America", Sales=9999},              new Customer { ID="B", City="Mumbai", Country="India", Region="Asia", Sales=8888},              new Customer { ID="C", City="Karachi", Country="Pakistan", Region="Asia", Sales=7777},              new Customer { ID="D", City="Delhi", Country="India", Region="Asia", Sales=6666},              new Customer { ID="E", City="São Paulo", Country="Brazil", Region="South America", Sales=5555 },              new Customer { ID="F", City="Moscow", Country="Russia", Region="Europe", Sales=4444 },              new Customer { ID="G", City="Seoul", Country="Korea", Region="Asia", Sales=3333 },              new Customer { ID="H", City="Istanbul", Country="Turkey", Region="Asia", Sales=2222 },              new Customer { ID="I", City="Shanghai", Country="China", Region="Asia", Sales=1111 },              new Customer { ID="J", City="Lagos", Country="Nigeria", Region="Africa", Sales=1000 },              new Customer { ID="K", City="Mexico City", Country="Mexico", Region="North America", Sales=2000 },              new Customer { ID="L", City="Jakarta", Country="Indonesia", Region="Asia", Sales=3000 },              new Customer { ID="M", City="Tokyo", Country="Japan", Region="Asia", Sales=4000 },              new Customer { ID="N", City="Los Angeles", Country="USA", Region="North America", Sales=5000 },              new Customer { ID="O", City="Cairo", Country="Egypt", Region="Africa", Sales=6000 },              new Customer { ID="P", City="Tehran", Country="Iran", Region="Asia", Sales=7000 },              new Customer { ID="Q", City="London", Country="UK", Region="Europe", Sales=8000 },              new Customer { ID="R", City="Beijing", Country="China", Region="Asia", Sales=9000 },              new Customer { ID="S", City="Bogotá", Country="Colombia", Region="South America", Sales=1001 },              new Customer { ID="T", City="Lima", Country="Peru", Region="South America", Sales=2002 }           };            var queryResult1 = from c in customers where c.Region == "Asia" select c; //条件查询            var queryResult2 = customers.Where(c => c.Region == "Asia");//lambda表达式,功能同1            //创建新对象            var queryResult3 = from c in customers where c.Region == "North America"                                select new { c.City, c.Country, c.Sales };//创建新对象            var queryResult4 = customers.Where(c => c.Region == "North America").                Select(c => new { c.City, c.Country, c.Sales });//lambda表达式,功能同3(注意此处调用顺序)            //Distinct()            var queryResult5 = (from c in customers select c.Region).Distinct();//查找出不重复的地区            var queryResult6 = customers.Select(c => c.Region).Distinct();//lambda表达式, 功能同5            //ALL和ANY            bool anyUSA = customers.Any(c => c.Country == "USA");//是否存在USA的客户            bool allAisa = customers.All(c => c.Region == "Asia");//是否全是Aisa客户            //多级排序            var queryResult7 = from c in customers                               orderby c.Region, c.Country, c.City                               select new { c.ID, c.Region, c.Country, c.City };            //升降序(ThenBy和ThenByDescending在OrderBy之后)            var queryResult8 = customers.OrderBy(c => c.Region).ThenByDescending(c => c.Country).                               ThenBy(c => c.City).Select(c => new { c.ID, c.Region, c.Country, c.City });            //组合查询            var queryResult9 = from c in customers group c by c.Region                                into cg select new { TotalSales = cg.Sum(c => c.Sales), Regioin = cg.Key };            var queryResult10 = from cg in queryResult9 orderby cg.TotalSales descending select cg;//各区域消费总额排名                       //Take() Skip()            queryResult9.Take(5);//前五            queryResult9.Skip(5);//跳过前五            //First() FirstOrDefault()            queryResult9.First();            queryResult9.FirstOrDefault();            //集运算符            //Interserct();Except();Union();            //Join            var queryResults =               from c in customers               join o in orders on c.ID equals o.ID               select new { c.ID, c.City, SalesBefore = c.Sales, NewOrder = o.Amount, SalesAfter = c.Sales + o.Amount };        }    }}

 

LINQTOSQL:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Saku{    class Program    {        private static DataClasses1DataContext dataContext = new DataClasses1DataContext();        public  static List<Teacher> stu = new List<Teacher>();        static void Main(string[] args)        {            var queryResult = from c in dataContext.Teacher where c.tID == "0001" select c;            var queryResult1 = dataContext.Teacher.Where(c => c.tID == "0001");            foreach(var item in queryResult1)            {                Console.WriteLine(item.tName);            }        }        static Teacher Add(Teacher t)//        {            dataContext.Teacher.InsertOnSubmit(t);            dataContext.SubmitChanges();            return t;        }        static Teacher Delete(Teacher t)//删除        {            dataContext.Teacher.DeleteOnSubmit(t);            dataContext.SubmitChanges();            return t;        }        static void Show()//遍历        {            foreach (Teacher tch in dataContext.Teacher)            {                Console.WriteLine(tch.tID + " " + tch.tName + " " + tch.tPassword + " " + tch.tPhone + " " + tch.tAcademy + " " + tch.tDepartment + " " + tch.tRole);            }        }        static bool Search(Teacher t)//查找        {            var queryResult = from n in dataContext.Teacher where n.tID == t.tID select n;            if(queryResult!=null)            {                Console.WriteLine("找到" + t.tID);                return true;            }            else            {                Console.WriteLine("没找到" + t.tID);                return false;            }        }        static void change()//        {            var t = dataContext.Teacher.SingleOrDefault(c => c.tID == "0001");            t.tPhone = "13437196351";            dataContext.SubmitChanges();        }    }}

 

未完待续。。

LinqToSql初探