C#第六节课

首先介绍了LINQ的用法

LINQ就是一个C#自带的数据库,实现的功能与主流的关系型数据库基本一致 ,它在对象领域和数据领域之间架起了一座桥梁,往往我们在编写日常的应用程序的时候很难绕开数据库的应用

在 Visual Studio 中,可以用 Visual Basic 或 C# 为以下数据源编写 LINQ 查询:SQL Server 数据库、XML 文档、ADO.NET 数据集,以及支持 IEnumerable 或泛型 IEnumerable<T> 接口的任意对象集合。 此外,还计划了对 ADO.NET Entity Framework 的 LINQ 支持,并且第三方为许多 Web 服务和其他数据库实现编写了 LINQ 提供程序。

LINQ 查询既可在新项目中使用,也可在现有项目中与非 LINQ 查询一起使用。 唯一的要求是项目应面向 .NET Framework 3.5 或更高版本。

首先我们创建了一个关于Customer的集合(Customer为自己定义的一个类)

然后创建了一个IEnumberable<Customer>用来存储查询的结果

 这里提一下关于LINQ的查询语句的写法

from 类型 in 集合

where 约束

select 要查询的键值

因为范围变量要放在最前面声明,所以from语句放在最前面

一个例子:

IEnumerable<Customer> result =
                from   customer  in customers
where customer.FirstName == "Donna"
select customer;

from 后面: range variable from the data source.

in 后面: Data source can be any collection that implements  System. Collections.

Generic. IEnumerable<T>

where后面的约束条件也可以用形如

customer.LastName.StartWith(“G”)

的更复杂的表达式

最后的select后面:

defines (or projects) the results.

the query returns the customer objects.

这样我们就完成了一个对简单的查询语句的认识

接下来看一下一个应用了LINQ的例子

// Example13-1.A simple LINQ query
using System;
using System.Collections.Generic;
using System.Linq;
namespace Programming_CSharp
{
    // Simple customer class
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
        // Overrides the Object.ToString() to provide a
        // string representation of the object properties.
        public override string ToString()
        {
            return string.Format("{0} {1}\nEmail:  {2}",
                        FirstName, LastName, EmailAddress);
        }
        
    }
     // Create a customer list with sample data
    
    public class Tester
    {
        private static List<Customer> CreateCustomerList()
        {
            List<Customer> customers = new List<Customer>
            {
                new Customer { FirstName = "Orlando",LastName = "Gee",
                                    EmailAddress = "orlando0@adventure-works.com"},
                new Customer { FirstName = "Keith", LastName = "Harris",
                                    EmailAddress = "keith0@adventure-works.com" },
                new Customer { FirstName = "Donna", LastName = "Carreras",
                                    EmailAddress = "donna0@adventure-works.com" },
                new Customer { FirstName = "Janet", LastName = "Gates",
                                    EmailAddress = "janet1@adventure-works.com" },
                new Customer { FirstName = "Lucy", LastName = "Harrington",
                                    EmailAddress = "lucy0@adventure-works.com" }
            };
            return customers;
        }
        static void Main()    // Main program
        {
            List<Customer> customers = CreateCustomerList();
            IEnumerable<Customer> result =  from customer in customers
            where  customer.FirstName == "Donna"  
            select customer;
            Console.WriteLine("FirstName == \"Donna\"");
            foreach (Customer customer in result)
            {    Console.WriteLine(customer.ToString());}
            customers[3].FirstName = "Donna";
            Console.WriteLine("FirstName == \"Donna\" (take two)");
            foreach (Customer customer in result)
            {  Console.WriteLine(customer.ToString());}
            Console.ReadLine();
        }
    }
}

这里是用的IEnumberable接口。

运行结果

我们可以看到首先我们第一次对集合进行firstname为donna的查询,得到了一个对象是donna carreras为关键字的

而当我们直接更改掉customers[3]的firstname的时候我们再次查询就可以得到所有Donna的对象

如上结果中

之后还有LINQ中提供累内联的函数也就是join

方式

 [data source 1] join [data source 2] on [join condition]

 

 并且注意LINQ的join子句仅在满足连接条件的对象在所有的数据源中都存在时才会返回结果。

var这个关键字是用来声明一个隐藏类型的

我们可以用var来声明一个没有类型的变量,不过并不是变量没有类型而是我们不用写C#会自动识别

var num = 2147483647;

这样的num就会被默认为是一个int而这样

var strstr = "2147483647";

strstr则会被认为是一个字符串

但是注意我们必须要在声明var的时候就给var赋初值(个人觉得这里类似于一个语法糖)

其实lambada表达式同样也是运用着这种感觉

lambada表达式这里介绍一下

形式:参数列表 => 语句或语句块

下列规则适用于 Lambda 表达式中的变量范围:
捕获的变量将不会被作为垃圾回收,直至引用变量的委托超出范围为止。
在外部方法中看不到 Lambda 表达式内引入的变量。
Lambda 表达式无法从封闭方法中直接捕获 ref 或 out 参数。
Lambda 表达式中的返回语句不会导致封闭方法返回。
Lambda 表达式不能包含其目标位于所包含匿名函数主体外部或内部的 goto 语句、break 语句或 continue 语句。
Lambda表达式的本质是“匿名方法”,即当编译我们的程序代码时,“编译器”会自动将“Lambda表达式”转换为“匿名方法”,如下例:
string[] names={"agen","balen","coure","apple"};
string[] findNameA=Array.FindAll<string>(names,delegate(string v){return v.StartsWith("a");});
string[] findNameB=Array.FindAll<string>(names,v=>v.StartsWith("a"));
上面中两个FindAll方法的反编译代码如下:
string[]findNameA=Array.FindAll<string>(names,delegate(stringv){returnv.StartsWith("a");});
string[]findNameB=Array.FindAll<string>(names,delegate(stringv){returnv.StartsWith("a");});
从而可以知道“Lambda表达式”与“匿名方法”是可以划上等号的,只不过使用“Lambda表达式”输写代码看上去更直观漂亮,不是吗?
所以。。。为了美观漂亮来说。lambada表达式确实存在意义非凡(其实我一直觉得程序语言的发展一定是越来越趋近人类语言。。。不过鉴于人类语言的模糊功能是在太过强大,可能还有很大差距,实际上我倒是觉得程序语言更适合表达一个观点什么的。。。脑洞)
恩,所以我的心里给lambada表达式的定义也是一个,恩,语法糖(而且可读性确实得到了提高)
 
ordering关键字则是用来给数据库中的内容进行排序以进行一些特殊的查找(跟顺序有关,顺带,如果没有形如年龄是第x大的学生是xxx这样的查找需求的时候建议不要排序,因为排序对数据库应用的开销算是很大的,毕竟在现在数据库的量级都是百万级别都算小的,信息爆炸,几亿几十亿的数据量并不少见,而基于比较的排序的理论复杂度下限也只能做到nlogn(可以几乎任何关于算法的书籍中看到证明)所以排序是一件,很累的事儿,如果没有需要就更不要随意排序)
之后又提到了xml的应用
其实现在很多的开发(因为自己也见识过一些应用的开发)前端和后台都是分开的,而前端是用来表现给用户的,后台是用来对前端传进来的数据进行运算判断的
比如登陆的时候你的用户名由网页(前端)传给后台,后台在数据库查找这个用户名和密码,然后判断是否正确返回给前端。
传递的方式则多种多样,xml就是其中之一
举例说明一个xml例子
<Customer>
  <FirstName>Orlando</FirstName>
  <LastName>Gee</LastName>
  <EmailAddress>orlando0@hotmail.com</EmailAddress>
</Customer>

这里的customer是一个类里面包含有三个数据就是firstname lastname和emailaddress

我们可以理解为一个大叔组,假如我们要将一大堆customer传进去也就是传一个customers就可以再外面再套一个<customers></customers>这样,然后里面罗列很多customer

这是关于xml

在C#中如何生成xml文档呢

 XmlElement firstNameElem 
       = customerXml.CreateElement("FirstName");
 firstNameElem.InnerText  
        = customer.FirstName;  //存入元素的值
//添加到customer元素
 customerElem.AppendChild(firstNameElem); 

这里注意要using System.xml;

这样就可以生成一个最简单的xml文件了

还是用之前的LINQ的那个集合生成一个xml代码

// Example13-1.A simple LINQ query
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
namespace Programming_CSharp
{
    // Simple customer class
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
        // Overrides the Object.ToString() to provide a
        // string representation of the object properties.
        public override string ToString()
        {
            return string.Format("{0} {1}\nEmail:  {2}",
                        FirstName, LastName, EmailAddress);
        }
        
    }
     // Create a customer list with sample data
    
    public class Tester
    {
        private static List<Customer> CreateCustomerList()
        {
            List<Customer> customers = new List<Customer>
            {
                new Customer { FirstName = "Orlando",LastName = "Gee",
                                    EmailAddress = "orlando0@adventure-works.com"},
                new Customer { FirstName = "Keith", LastName = "Harris",
                                    EmailAddress = "keith0@adventure-works.com" },
                new Customer { FirstName = "Donna", LastName = "Carreras",
                                    EmailAddress = "donna0@adventure-works.com" },
                new Customer { FirstName = "Janet", LastName = "Gates",
                                    EmailAddress = "janet1@adventure-works.com" },
                new Customer { FirstName = "Lucy", LastName = "Harrington",
                                    EmailAddress = "lucy0@adventure-works.com" }
            };
            return customers;
        }
        static void Main()    // Main program
        {
            List<Customer> customers = CreateCustomerList();
            // Find customer by first name 
            XmlDocument customerXml = new XmlDocument();
            XmlElement rootElem = customerXml.CreateElement("Customers");
            customerXml.AppendChild(rootElem);

            foreach (Customer customer in customers)
            {
                // Create new element representing the customer object.
                XmlElement customerElem = customerXml.CreateElement("Customer");
  
                // Add element “FirstName” property to the customer element.
                XmlElement firstNameElem = customerXml.CreateElement("FirstName");
                firstNameElem.InnerText  = customer.FirstName;
                customerElem.AppendChild(firstNameElem);
                // Add element: LastName property  to the customer element.
                XmlElement lastNameElem = customerXml.CreateElement("LastName");
                lastNameElem.InnerText = customer.LastName;
                customerElem.AppendChild(lastNameElem);

                // Add element: EmailAddress property to the customer element.
                XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
                emailAddress.InnerText = customer.EmailAddress;
                customerElem.AppendChild(emailAddress);

                // Finally add the customer element to the XML document
                rootElem.AppendChild(customerElem);
            }
            Console.WriteLine(customerXml.OuterXml);

            Console.ReadLine();
        }
    }
}

生成的结果是

<Customers>
  <Customer>
    <FirstName>Orlando</FirstName>
    <LastName>Gee</LastName>
    <EmailAddress>orlando0@hotmail.com</EmailAddress>
  </Customer>
  <Customer>
    <FirstName>Keith</FirstName>
    <LastName>Harris</LastName>
    <EmailAddress>keith0@hotmail.com</EmailAddress>
  </Customer>
   <> ….</>
</Customers>

这节课的知识复习到这里,因为xml还有一些细致的并没有弄懂。。。至此已经能生成建议的xml了~

因为课堂内容讲述较快,所以课下的压力略有增加,感觉有点吃不太透,要更加努力了,以上!

posted on 2015-04-26 20:40  Snorlax  阅读(330)  评论(1编辑  收藏  举报