asp.net linq用法與object用法

來源:互聯網
上載者:User

:linq是什嗎? 

linq可以理解為嵌入C#文法的強型別查詢語言。(注意:儘管linq看起來和Sql查詢很像,但文法卻不相同。)

二:linq的作用?
提供一種統一且對稱的方式,讓程式員得到資料和操作資料(此處的資料可以是XML,DataSet,物理資料等) 

查詢數組

int[] arr = new int[] {5, 1, 9, 3, 4, 0, 8 };
var m = from item in arr
        select item;
foreach (var item in m)
{
    Response.Write(item.ToString() + "<br>");
}
結果:

5
1
9
3
4
0
8

可以看出 LINQ 和 SQL 很像,兩點不同:

select 在後面,這可能是受某些限制,只好把 select 放在後面。
from 與資料之間多了個“變數名 in”。
查詢 List

System.Collections.Generic.List<int> arr = new System.Collections.Generic.List<int> { 5, 1, 9, 3, 4, 0, 8 };
var m = from item in arr
        select item;
foreach (var item in m)
{
    Response.Write(item.ToString() + "<br>");
}

可以看出查詢 List 與查詢數組完全是一樣的。另請參見 C# 3.0 -集合初始化設定。

查詢

Dictionary

System.Collections.Generic.Dictionary<int, int> arr = new System.Collections.Generic.Dictionary<int, int>();
arr.Add(0, 5);
arr.Add(1, 1);
arr.Add(2, 9);
arr.Add(3, 3);
arr.Add(4, 4);
arr.Add(5, 0);
arr.Add(6, 8);
var m = from item in arr
        select item;
foreach (var item in m)
{
    Response.Write(item.Value.ToString() + "<br>");
}

我們可以發現在查詢 Dictionary 時,查詢語句是一樣的,但輸出時,不再是 item.ToString(),而是 item.Value.ToString(),並且我們在寫完“item.”後,“Value”會自動出現 IntelliSense 中,不需要我們記憶。


返回時建立對象

string[] files = System.IO.Directory.GetFiles("C:");
var fis = from file in files
          select new System.IO.FileInfo(file);
foreach (var fi in fis)
{
    Response.Write(fi.Name + " " + fi.CreationTime.ToString() + "<br>");
}

上述先把 C: 下的檔案放到 files 字串數組中,然後在 LINQ 查詢時,將其“封裝”成 FileInfo 對象。注意這裡使用了 var。

返回時建立匿名型別

int[] arr = new int[] { 5, 1, 9, 3, 4, 0, 8 };
var m = from item in arr
        select new { a = item, b = item + 1 };
foreach (var item in m)
{
    Response.Write(item.b.ToString() + "<br>");
}

使用 {},具體請參見 C# 3.0 -匿名型別。

使用 where、orderby

int[] arr = new int[] { 5, 1, 9, 3, 4, 0, 8 };
var m = from item in arr
        where item > 3
        orderby item descending
        select item;
foreach (var item in m)
{
    Response.Write(item.ToString() + "<br>");
}

注意 orderby 是連在一起的,而不是 order by;還有等於判斷是“==”,而不是“=”。您可能會說 descending 多難寫啊,不如 SQL 的 desc,其實不必擔心,Visual Web Developer 和 Visual Studio 都有智能提示的。

 

三:linq可應用在哪些情境?
Linq to Object、Linq to XML、Linq to DataSet、Linq to Entities、Parallel Linq(平行處理linq查詢返回的資料)

linq的基本文法:var result = from item in container select item; 

linq擷取資料子集: var result = from item in container where booleanexpression select item;

linq to object 例子

        static void QueryStrings()
        {
            string[] games = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2" };
            //構建一個查詢運算式(注意:ling運算式在迭代內容之前,他們不會真正的運行計算)//linq此時還沒有運算
            //linq查詢的結果集,應該總是使用隱式類型,在絕大數情況下,真正的傳回值實現了泛型 IEnumerable<T>介面的類型
            var subset = from g in games where g.Contains(" ") orderby g select g;
            //上面代碼也可以寫成 IEnumerable<string> subset = from g in games where g.Contains(" ") orderby g select g;
            //輸出結果。在迭代的時候才運算(這叫:順延強制)
            foreach (string s in subset)
            {
                Console.WriteLine("含有空格的是:{0}",s);
            }
        }

 

 


linq在迭代外運算例子:

       //在foreach邏輯外運算linq
        static void QueryInt()
        {
            //如果希望在foreach邏輯外表運算Linq運算式,可以調用有Enumerable類型定義的擴充方法。如ToArray<T>()、ToList<T>()等。
            int[] numbers = { 2, 10, 30, 15, 1, 22 };
            //立即擷取資料
            int[] rst =( from i in numbers where i >10 orderby i select i).ToArray<int>();

        }

 

 


linq查詢中的常用函數
1.count<T>() 擷取linq查詢運算式返回的項數

        static void FunLinq()
        {
            int[] numbers = { 2, 10, 30, 15, 1, 22 };
            //輸出大於10的總數
            int count = (from i in numbers where i > 10 orderby i select i).Count<int>();
            Console.WriteLine(count);//輸出:3
        }

 

 


2.Reverse<T>對linq結果集中的項進行反轉

      var newnumbers = from i in numbers select i;
            foreach (var p in numbers.Reverse())
            {
                Console.WriteLine(p);//輸出22 1 15 30 10 2
            }

 

 


3.orderby 對linq進行排序,預設是正序

       //排序(正序)
            string[] games = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2" };
            var newn = from i in games orderby i ascending select i;
            foreach (var p in games)
            {
                Console.Write(p+",");//
            }

 


4.Distinct()移除資料中的重複項目    //排序(正序)

            string[] games = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "Shock2", "Shock2"};
            var newn = from i in games orderby i ascending select i;
            foreach (var p in games.Disinct())
            {
                Console.Write(p+",");//
            }

 


5.彙總操作

 

//彙總操作


            //最大值
            var maxi =( from i in games orderby i ascending select i).Max();
            //最小值
            var mini = (from i in games orderby i ascending select i).Min();
            //平均值
            var avar = (from i in numbers orderby i ascending select i).Average();
            //總和
            var sum = (from i in numbers orderby i ascending select i).Sum();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.