LINQ

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Linq.SqlClient;
using System.Linq;
using System.IO;

namespace ThreadingTester
{

    [Table(Name = "Customers")]
    public class Customer
    {

        [Column(IsPrimaryKey = true)]
        public string CustomerID { get; set; }

        [Column(Name = "ContactName")]
        public string Name { get; set; }

        [Column]//如果没有指定Column特性的Name属性,那么系统会把属性名作为数据表的字段名,也就是说实体类的属性名就需要和数据表中的字段名一致。
        public string City { get; set; }


        public string Country
        {
            get;
            set;
        }

        public string CompanyName
        {
            get;
            set;
        }
        public string Phone
        {
            get;
            set;
        }
        public string ContactName
        {
            get;
            set;
        }
        public string Orders
        {
            get;
            set;
        }

    }


    public class LINQ
    {
        static void Main44(string[] args)
        {
            List<Product> Products = new List<Product>();
            Product model1 = new Product();
            model1.CategoryID = 3;
            model1.Discontinued = false;
            model1.SupplierID = 6;
            model1.UnitPrice = 466;

            Product model2 = new Product();
            model2.CategoryID = 743;
            model2.Discontinued = false;
            model2.SupplierID = 6;
            model2.UnitPrice = 466;

            Product model3 = new Product();
            model3.CategoryID = 379;
            model3.Discontinued = false;
            model3.SupplierID = 64;
            model3.UnitPrice = 65466;

            Product model4 = new Product()
            {
                CategoryID = 8,
                Discontinued = false,
                SupplierID = 45,
                UnitPrice = 74,
            };

            Products.Add(model1);
            Products.Add(model2);
            Products.Add(model3);
            Products.Add(model4);

            List<Customer> Customers = new List<Customer>();
            List<Employee> Employees = new List<Employee>();
            List<Order> Orders = new List<Order>();
           

            //Count
            var q3366 = Products.Count();//简单形式
            q3366 = Products.Count(p => !p.Discontinued);//带条件形式
            var q = Products.LongCount();//返回LONG类型,对于元素个数较多的集合可视情况可以选用

            //Sum
            var q2 = Products.Select(o => o.CategoryID).Sum();//简单形式, 得到所有CategoryID的和
            q2 = Products.Sum(p => p.CategoryID); ;//映射形式, 得到所有CategoryID的和

            //Min
            var q22 = Products.Select(p => p.CategoryID).Min();//简单形式,查找任意产品的最低单价
            q22 = Products.Min(p => p.CategoryID);// 映射形式
            var q33 = from p in Products
                      group p by p.CategoryID into g
                      select new
                      {
                          g.Key,
                          NumProducts = g.Min(p => p.Discontinued)
                      };//查找每个类别中Discontinued最低的记录

            //Average
            var q36 = Products.Select(p => p.CategoryID).Average();//简单形式 ,返回CategoryID的平均值 ,其返回值类型为double
            var q3 = Products.Average(p => p.UnitPrice);//映射形式,得到所有产品的平均单价
            //Console.WriteLine(q36);
            var categories = from p in Products
                             group p by p.CategoryID into g
                             select new
                             {
                                 g.Key,
                                 ExpensiveProducts =
                                     from p2 in g
                                     where p2.UnitPrice > g.Average(p3 => p3.UnitPrice)
                                     select p2
                             };//查找每个类别中单价高于该类别平均单价的产品

 

            //orderby
            //按多个表达式进行排序,例如先按CategoryID排序,当CategoryID相同时,按Discontinued排序。这一句用Lambda表达式像这样写:
            var q4 = from c in Products.OrderBy(c => c.CategoryID).ThenBy(c => c.Discontinued).ToArray().OrderByDescending(c => c.UnitPrice) select c;

            //OrderBy操作,不支持按type排序,也不支持匿名类
            //var q5 = Products.OrderBy(c => new
            //{
            //    c.UnitPrice,
            //    c.SupplierID
            //}).ToList();//会被抛出异常


            //Any
            //用于判断集合中是否有元素满足某一条件;不延迟。(若条件为空,则集合只要不为空就返回True,否则为False)。有2种形式,分别为简单形式和带条件形式。
            //简单形式:仅返回没有订单的客户:
            //var q44 = from c in Products where !c.CategoryID.Any() select c;

            //带条件形式:仅返回至少有一种产品断货的类别:
            //var q555 = from c in Products  where c.SupplierID.Any(p => p.Discontinued) select c;


            string[] customerID_Set = new string[] { "AROUT", "BOLID", "FISSA" };
            var q444 = (from o in Products where customerID_Set.Contains(o.StringTest) select o).ToList();
            q444 = (from o in Products where (new string[] { "AROUT", "BOLID", "FISSA" }).Contains(o.StringTest) select o).ToList();

            //包含一个对象s
            var order = (from o in Products
                         where o.CategoryID == 10248
                         select o).First();
            //var q4465 = Products.Where(p => p.CategoryID.Contains(order)).ToList();
            //foreach (var cust in q)
            //{
            //    foreach (var ord in cust.Orders)
            //    {
            //        //do something
            //    }
            //}
            //原先很复杂的SQL使用查询句法会很简单(比如按照条件分组)。但是原先觉得很好理解的SQL使用查询句法会觉得很复杂(比如连接查询)。其实,我们还可以通过其它方式进行连接操作。虽然Linq to sql已经非常智能了,但是对于非常复杂的查询还是建议通过存储过程实现,

            //2.包含多个值:语句描述:这个例子使用Contains查找其所在城市为西雅图、伦敦、巴黎或温哥华的客户。
            string[] cities = new string[] { "Seattle", "London", "Vancouver", "Paris" };
            var q9 = Products.Where(p => cities.Contains(p.StringTest)).ToList();


            //Concat (连接)连接不同的集合,不会自动过滤相同项
            var q789 = (from c in Products select c.StringTest).Concat(from c in Products select c.StringTest).Concat(from e in Products select e.StringTest);//说明:连接不同的集合 返回所有消费者和雇员的电话和传真。

            var q55 = (from c in Customers select new { Name = c.CompanyName, c.Phone }).Concat(from e in Employees select new { Name = e.FirstName + " " + e.LastName, Phone = e.HomePhone });//.Concat 复合形式

            // Union (合并)连接不同的集合,自动过滤相同项,即是将两个集合进行合并操作,过滤相同的项
            var q57 = (from c in Customers select c.Country).Union(from e in Employees select e.Country);

            //Intersect 获取不同集合的相同项(交集)。即先遍历第一个集合,找出所有唯一的元素,然后遍历第二个集合,并将每个元素与前面找出的元素作对比,返回所有在两个集合内都出现的元素。
            var q555 = (from c in Customers select c.Country).Intersect(from e in Employees select e.Country);//查询顾客和职员同在的国家。

            //Except(与非)说明:排除相交项;延迟。即是从某集合中删除与另一个集合中相同的项。先遍历第一个集合,找出所有唯一的元素,然后再遍历第二个集合,返回第二个集合中所有未出现在前面所得元素集合中的元素。
            var b5 = (from c in Customers select c.Country).Except(from e in Employees select e.Country);//查询顾客和职员不同的国家。


            var b53 = from c in Customers where (from o in Orders group o by o.ShippedID into o where o.Count() > 5 select o.Key).Contains(55) select c;//子查询 查询订单数超过5的顾客信息

            var B47 = from c in Customers where new string[] { "Brandenburg", "Cowes", "Stavern" }.Contains(c.City) select c;//in操作 描述:查询指定城市中的客户

            //---------------------------------------------------------------------------------------
            //var innerjoin = from p in ctx.Products
            //                join c in ctx.Categories
            //                on p.CategoryID equals c.CategoryID
            //                select p.ProductName; //join 描述:内连接,没有分类的产品查询不到

            //对应SQL:
            //SELECT COUNT(*) AS [value]
            //FROM [dbo].[Products] AS [t0]
            //INNER JOIN [dbo].[Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[CategoryID])

            //---------------------------------------------------------------------------------------
            // left join 是left outer join的简写,left join默认是outer属性的。
            //            外连接,没有分类的产品也能查询到 查询句法:
            //var leftjoin = from p in ctx.Products
            //                       join c in ctx.Categories
            //                       on p.CategoryID equals c.CategoryID
            //                       into pro
            //                       from x in pro.DefaultIfEmpty()
            //                       select p.ProductName;

            //                对应SQL:
            //                SELECT COUNT(*) AS [value]
            //                FROM [dbo].[Products] AS [t0]
            //                LEFT OUTER JOIN [dbo].[Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[CategoryID])

            //---------------------------------------------------------------------------------------


            String path = @"C:\Northwind.map";
            XmlMappingSource xms = XmlMappingSource.FromXml(File.ReadAllText(path));
            Jhgongan ctx = new Jhgongan("server=(local);database=jhgongan;uid=sa;pwd=88226959", xms);//使用sqlmetal可以很方便的同步数据库与实体和映射文件。每次修改数据库结构,从dbml设计器上删除表、存储过程然后再重新添加也是很麻烦的事情。

 


            // Top/Bottom操作适用场景:适量的取出自己想要的数据,不是全部取出,这样性能有所加强。
            var q58 = (from e in Employees orderby e.HireDate select e).Take(5);//选择所雇用的前5个雇员。

            //Skip 说明:跳过集合的前n个元素;延迟。即我们跳过给定的数目返回后面的结果集。
            var q46 = (from p in Products orderby p.UnitPrice descending select p).Skip(10);// 选择10种最贵产品之外的所有产品。

            //结合Skip和Take就可实现对数据分页操作。
            var q76 = (from c in Customers orderby c.ContactName select c).Skip(50).Take(10);//语句描述:使用Skip和Take运算符进行分页,跳过前50条记录,然后返回接下来10条记录,因此提供显示Products表第6页的数据
            var qrr = (from p in Products where p.ProductID > 50 orderby p.ProductID select p).Take(10);//此方法仅适用于按唯一键排序的情况。

            // Like 自定义的通配表达式。%表示零长度或任意长度的字符串;_表示一个字符;[]表示在某范围区间的一个字符;[^]表示不在某范围区间的一个字符。比如查询消费者ID以“C”开头的消费者。 
            var q44 = from c in Customers where SqlMethods.Like(c.CustomerID, "C%") select c;
            q44 = from c in Customers where !SqlMethods.Like(c.CustomerID, "A_O_T") select c;//查询消费者ID没有“AXOXT”形式的消费者
            var q4d = from o in Orders where SqlMethods.DateDiffDay(o.OrderDate, o.ShippedDate) < 10 select o;//查询在创建订单后的 10 天内已发货的所有订单 ,在两个变量之间比较。分别有:DateDiffDay、DateDiffHour、DateDiffMillisecond、DateDiffMinute、DateDiffMonth、DateDiffSecond、DateDiffYear 

            DataContext db = new DataContext("server=(local);database=jhgongan;uid=gfdgfd;pwd=gfdgfd");
            var newCustomer = new Customer
            {
                CustomerID = "MCSFT",
                CompanyName = "Microsoft",
                ContactName = "John Doe",

            };

 

            //db.Customers.InsertOnSubmit(newCustomer);
            //db.SubmitChanges();

            //-----------------------------------
            var custs = from c in Customers where c.City == "Sao Paulo" select c;
            //上面的查询句法不会导致语句立即执行,仅仅是一个描述性的语句,只有需要的时候才会执行它
            foreach (var cust in custs)
            {
                foreach (var ord in cust.Orders)
                {
                    //同时查看客户数据和订单数据
                }
            }
            //-----------------------------------
            var q47 = from c in Customers where c.City == "London" select c;
            Customer[] qArray = q47.ToArray();//这个例子使用 ToArray 将查询直接计算为数组。

            var q48 = from e in Employees where e.HireDate >= new DateTime(1994, 1, 1) select e;
            List<Employee> qList = q48.ToList();//将序列转换为泛型列表

            //将序列转化为字典,使用Enumerable.ToDictionary<TSource, TKey>方法可以将序列转化为字典。TSource表示source中的元素的类型;TKey表示keySelector返回的键的类型。其返回一个包含键和值的Dictionary<TKey, TValue>。
            var q486 = from p in Products where p.UnitsInStock <= p.ReorderLevel && !p.Discontinued select p;
            Dictionary<int, Product> qDictionary = q486.ToDictionary(p => p.ProductID);
            foreach (int key in qDictionary.Keys)
            {
                Console.WriteLine(key);
            }
            //-----------------------------------
            //新建一个标准的ADO.NET连接:
            //string connString = string.Empty;
            //SqlConnection nwindConn = new SqlConnection(connString);
            //nwindConn.Open();
            //// ... 其它的ADO.NET数据操作代码... //
            ////利用现有的ADO.NET连接来创建一个DataContext:
            //Northwind interop_db = new Northwind(nwindConn);
            //var orders =
            //     from o in interop_db.Orders
            //     where o.Freight > 500.00M
            //     select o;
            ////返回Freight>500.00M的订单
            //nwindConn.Close();
            //-----------------------------------
        }
    }
    //-----------------------------------
    //对于一些在项目中经常被用到的查询可以封装成已编译查询,这样就能提高执行效率:
    static class Queries
    {
        public static Func<Jhgongan, string, IQueryable<T_Affiche>> CustomersByCity = CompiledQuery.Compile((Jhgongan ctx, string city) => from c in ctx.T_Affiche where c.Content == city select c);

    }
    //调用查询方式如下:   
    // GridView1.DataSource = Queries.CustomersByCity(ctx, "London");
    // GridView1.DataBind();
    //-----------------------------------


    class Program333
    {
        static void Main44()
        {
            List<String> names = new List<String>();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");

            // Display the contents of the list using the Print method.
            names.ForEach(Print);

            // The following demonstrates the anonymous method feature of C#
            // to display the contents of the list to the console.
            names.ForEach(delegate(String name)
            {
                Console.WriteLine(name);
            });
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

 


}

posted on 2011-11-15 22:33  breakpoint  阅读(217)  评论(0编辑  收藏  举报

导航