C#Linq簡介

LInq是Language Integrated Query的簡稱,它是微軟在.net framework 3.5里面新加入的特性,用以簡化查詢查詢操作。它主要包含了3塊,Linq to Object、Linq to SQL、Linq to XML,其中Linq to Object和對于對象的查詢,Linq to XML則又提供了對XML格式數(shù)據(jù)的檢索、設(shè)置等功能,其中值得關(guān)注的Linq to SQL是我們要重點掌握的,因為它改變了我們傳統(tǒng)的對于SQL操作的認識。

成都創(chuàng)新互聯(lián)公司服務(wù)項目包括青河網(wǎng)站建設(shè)、青河網(wǎng)站制作、青河網(wǎng)頁制作以及青河網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,青河網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到青河省份的部分城市,未來相信會繼續(xù)擴大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!

一、Linq to Object

先上一段代碼:

string[] contries = new string[] { "china", "russia", "american", "spain", "japan", "china" };
var query = from c in contries select c;//Linq to object
IEnumerator enumerator = query.GetEnumerator();
while (enumerator.MoveNext())
{
    Console.WriteLine(enumerator.Current);
}

注意Linq to Object的語法,from c in contries select c ; // 這里的c任意起名,in后面的contries 為數(shù)組對象或者是列表、集合等對象,select c 與前面的c保持一致。這是Linq強大的地方,試想我們以前要想查詢數(shù)組里面的每一個元素要寫一層for循環(huán)然后循環(huán)輸出。這里似乎看不出什么明顯優(yōu)勢的地方,我們繼續(xù)往下看。

var query = from c in contries select c;
替換為:
var query = from c in contries.Distinct() where c.Length == 5 orderby c ascending select c;

我們會發(fā)現(xiàn)利用linq可以很容易的像利用sql語句一樣查詢、排序,如果利用原始的技術(shù)可能要多些好幾行代碼!

再舉個例子。

這是論壇某個壇友發(fā)的帖子,問如何用Linq進行分組查詢。見linq分組統(tǒng)計。

我在里面給出了解答,當然了里面的List完全可以是從數(shù)據(jù)庫中獲取,我簡單模擬了一下,代碼如下。

定義1個實體類:

public class Product
{
    public Product(string province, Int32 value)
    {
        this.Province = province;
        this.Value = value;
    }
                                                          
    public string Province { get; set; }
    public Int32 Value { get; set; }
}

然后在Main函數(shù)中輸入:

var result = from p in list.AsEnumerable()
             group p by p.Province into g
             select new
             {
                 g.Key,
                 SumValue = g.Sum(p => p.Value)
             };
result.ToList().ForEach((i) =>
{
    Console.WriteLine(i.Key + ":" + i.SumValue);
});

可以得到分組統(tǒng)計的結(jié)果。

再附一個簡單排序的例子。linq排序

二、Linq to SQL

這是Linq技術(shù)的重頭戲,當然現(xiàn)在有了EntityFramework等技術(shù),但是我們還是可以關(guān)注一下。

我們新建兩張表,很簡單。

C# Linq簡介

然后在項目中新建一個Linq to SQL類,切換到設(shè)計界面。同時打開服務(wù)資源管理器,添加數(shù)據(jù)連接,連接到數(shù)據(jù)庫。拖動classInfo和studentInfo兩張表到Linq to SQL類文件的設(shè)計界面,我們會發(fā)現(xiàn)關(guān)系替我們都準備的好好的。

C# Linq簡介

C# Linq簡介

OK,這時就可以寫相應(yīng)代碼,進行添加操作了。

DataClasses1DataContext datacontext = new DataClasses1DataContext();
classInfo classInfo = new classInfo()
{
    classId = 1,
    className = "grade1"
};
datacontext.classInfo.InsertOnSubmit(classInfo);
                                                 
studentInfo studentInfo = new studentInfo()
{
    studentId = "001",
    studentName = "liming",
    classId = 1
};
                                                 
datacontext.studentInfo.InsertOnSubmit(studentInfo);
                                                 
datacontext.SubmitChanges();

這樣就添加了1條班級記錄和1條學(xué)生記錄。

如果我們要刪除一條學(xué)生記錄怎么辦?舉個例子,鍵入如下代碼:

DataClasses1DataContext datacontext = new DataClasses1DataContext();
studentInfo studentInfo = datacontext.studentInfo.Single(c => c.studentName == "liming");
datacontext.studentInfo.DeleteOnSubmit(studentInfo);
datacontext.SubmitChanges();

這樣就把liming這個學(xué)生記錄給刪除了,很簡單吧?

好,現(xiàn)在我們修改這個學(xué)生記錄,把名字改成zhang3。

DataClasses1DataContext datacontext = new DataClasses1DataContext();
studentInfo studentInfo = datacontext.studentInfo.Single(c => c.studentName == "liming");
studentInfo.studentName = "zhang3";//直接賦新的值
datacontext.SubmitChanges();//提交更改就可以了

補充一點很重要的,就是如何用linq to sql來進行查詢操作。

前面的Single其實就是一種查詢操作,返回單個對象。

直接上一個linq帶條件的分頁查詢實例:

DataClasses1DataContext datacontext = new DataClasses1DataContext();
                                 
var singleStudent = from s in datacontext.studentInfo
                    where s.studentName != "zhang3"
                    orderby s.classInfo descending
                    select s;
                                 
IList<studentInfo> studentList = singleStudent.Skip(pageSize * (pageNumber - 1)).Take(pageSize).ToList();
foreach (studentInfo student in studentList)
{
    Console.WriteLine("studentId:" + student.studentId + "studentName:" + student.studentName);
}

三、Linq to XML

以前我們操作XML一般都用XmlDocument、XmlReader等核心類去處理,關(guān)于這個我在點擊打開鏈接這個帖子中已經(jīng)簡單總結(jié)了一把。這里我們看看Linq是怎么處理XML的。

1、創(chuàng)建XML

XElement contacts =
    new XElement("Students",
    new XElement("Student",
        new XElement("Name", "Xiao Ming"),
        new XElement("Phone", "99599",
        new XAttribute("Type", "Home")),
        new XElement("phone", "010-99599",
        new XAttribute("Type", "Work")),
        new XElement("Address",
            new XElement("Street", "123 Street"),
            new XElement("City", "123 City"),
            new XElement("State", "1"),
            new XElement("Postal", "0000000")
        )
    )
);
contacts.Save("test.xml");

你會發(fā)現(xiàn),你只要記住XElement這一個核心類就可以使用Linq創(chuàng)建xml,而且編碼的方式很輕松,就是在表達一個xml的層級關(guān)系。

效果如下:

<?xml version="1.0" encoding="utf-8"?>
<Students>
  <Student>
    <Name>Xiao Ming</Name>
    <Phone Type="Home">99599</Phone>
    <phone Type="Work">010-99599</phone>
    <Address>
      <Street>123 Street</Street>
      <City>123 City</City>
      <State>1</State>
      <Postal>0000000</Postal>
    </Address>
  </Student>
</Students>

2、查詢XML

還是用上面生成的XML來做測試,鍵入如下代碼:

XElement root = XElement.Load("test.xml");
IEnumerable address = from el in root.Elements("Student").Elements("phone")
                      where el.Attribute("Type").Value == "Work"
                      select el;
                   
foreach (XElement el in address)
{
    Console.WriteLine(el.Value);
}

輸出:010-99599。

四、Linq to DataTable

意思跟Linq to Object是一樣的,應(yīng)該屬于Linq to Object的范疇,這里單獨拿出來,分享一下。

舉個例子,對兩個DataTable的數(shù)據(jù)進行合并,原貼見:兩個DataTable合并列。

先構(gòu)造兩個DataTable。

DataTable A = new DataTable();
A.Columns.Add("NameNumber", typeof(string));
A.Columns.Add("Type", typeof(string));
               
DataRow drA = null;
drA = A.NewRow();
drA["NameNumber"] = "111";
drA["Type"] = "Y";
A.Rows.Add(drA);
               
drA = A.NewRow();
drA["NameNumber"] = "222";
drA["Type"] = "N";
A.Rows.Add(drA);
               
DataTable B = new DataTable();
B.Columns.Add("NameNumber", typeof(string));
B.Columns.Add("Name", typeof(string));
B.Columns.Add("Address", typeof(string));
               
DataRow drB = null;
drB = B.NewRow();
drB["NameNumber"] = "111";
drB["Name"] = "張三";
drB["Address"] = "上海";
B.Rows.Add(drB);
               
drB = B.NewRow();
drB["NameNumber"] = "222";
drB["Name"] = "李四";
drB["Address"] = "北京";
B.Rows.Add(drB);

然后我們通過Linq to DataTable進行合并。

var result = from p in A.AsEnumerable()
             from q in B.AsEnumerable()
             where p.Field<string>("NameNumber") == q.Field<string>("NameNumber")
             select new
             {
                 NameNumber = p.Field<string>("NameNumber"),
                 Type = p.Field<string>("Type"),
                 Address = q.Field<string>("Address")
             };
result.ToList().ForEach(x => Console.WriteLine(x.NameNumber + "-" + x.Type + "-" + x.Address));

效果圖下:

C# Linq簡介

文章名稱:C#Linq簡介
本文URL:http://muchs.cn/article36/ihggsg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、網(wǎng)站內(nèi)鏈建站公司、商城網(wǎng)站企業(yè)網(wǎng)站制作、用戶體驗

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司