天天看點

LINQ TO OBJECT

                            linq to object

轉自:彙智網~!

http://www.hubwiz.com/

概述:

    linq to object是用于操作記憶體對象的linq程式設計接口,包含了大量的查詢操作符,針對記憶體中的集合對象進行操作。

  linq to object的實作基于ienumerable<t>泛型接口、序列(sequences)以及标準查詢操作符(standard query operators)等基本概念。其中,ienumerable<t>泛型接口是使用c# 2.0泛型技術實作的一個接口,該接口與ienumerable類似,允許對接口内部的元素進行列舉操作;序列是一個專門術語,表示一個實作了ienumerable<t>接口的集合對象。

  linq to object的大部分操作是針對序列的。标準查詢操作符本質上是一些擴充方法,這些擴充方法定義在靜态類system.linq.enumerable中,其原型的第一個參數(帶this修飾符的參數)是ienumerable<t>類型。由于這些方法都是擴充方法,它們可以在ienumerable<t>執行個體對象上直接調用,無需為調用傳遞一個類型為ienumerable<t>的對象作為第一個參數。

  要在代碼中使用linq to object标準查詢操作符,需要在代碼中添加using system.linq指令,以引入必要的命名空間。我們在後面的課程中将學習linq to object的一些操作符。

        selectmany将序列的每個元素投影到 ienumerable<t> 并将結果序列合并為一個序列。用法如下代碼:

static void main()

{

 string[] text = { "albert was here",

                   "burke slept late",

                   "connor is happy" };

 // selectmany合并并傳回一個新序列

 var tt = text.selectmany((s, index) => from ss in s.split(' ')

         select new { word = ss, index = index });

 foreach (var n in tt)

   console.writeline("{0}:{1}", n.word,n.index);

}

運作結果為:

albert:0

was:0

here:0

burke:1

slept:1

late:1

connor:2

is:2

happy:2

   take操作符用于從輸入序列中傳回指定數量的元素。用法如下代碼:

    int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

    //對數組降序排序并取出前三個記錄

    ienumerable<int> topthreegrades =

           grades.orderbydescending(grade => grade).take(3);

    console.writeline("the top three grades are:");

    foreach (int grade in topthreegrades)

    {

        console.writeline(grade);

    }

the top three grades are:

98

92

85

     takewhile操作符用于從輸入序列中返加指定數量且滿足一定條件的元素。用法如下代碼:

  string[] fruits = { "apple", "banana", "mango",

                      "orange","passionfruit", "grape" };

  //takewhile用法

  ienumerable<string> query =fruits.takewhile(

             fruit => string.compare("orange", fruit, true) != 0);

  foreach (string fruit in query)

  {

       console.writeline(fruit);

  }

運作結果為:

apple

banana

mango

    skip用于從輸入序列中跳過指定數量的元素,傳回由序列中剩餘元素所組成的新元素。用法如下代碼:

    int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

    ienumerable<int> lowergrades =

    grades.orderbydescending(g => g).skip(3);

    console.writeline("all grades except the top three are:");

 foreach (int grade in lowergrades)

 {

     console.writeline(grade);

 }

all grades except the top three are:

82

70

59

56

      takewhile操作符用于跳過滿足一定條件指定數量的元素。用法如下代碼:

      int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

      // skipwhile的用法

      ienumerable<int> lowergrades =

      grades.orderbydescending(grade => grade).skipwhile(grade => grade >= 80);

      console.writeline("all grades below 80:");

      foreach (int grade in lowergrades)

      {

          console.writeline(grade);

       }

all grades below 80:

             distinct去除一個序列裡相同的元素。用法如下代碼:

   list<int> ages = new list<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

   //distinct的用法

   ienumerable<int> distinctages = ages.distinct();

   console.writeline("distinct ages:");

   foreach (int age in distinctages)

   {

       console.writeline(age);

   }

distinct ages:

21

46

55

17

   intersect将同時存在于兩個序列中的元素挑選出來,組成一個新的序列。代碼如下:

   int[] id1 = { 44, 26, 92, 30, 71, 38 };

   int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };

   //intersect用法

   ienumerable<int> both = id1.intersect(id2);

   foreach (int id in both)

           console.writeline(id);

26

30

    except 傳回兩個序列中隻存在于第一個序列而不存在于第二個序列中的元素所組成的新序列。用法如下代碼:

 double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };

 double[] numbers2 = { 2.2 };

 //except用法

 ienumerable<double> onlyinfirstset = numbers1.except(numbers2);

 foreach (double number in onlyinfirstset)

         console.writeline(number);

2

2.1

2.3

2.4

2.5

     first用于傳回輸入序列的第一個元素或滿足條件的第一個元素。

   int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,

   83, 23, 87, 435, 67, 12, 19 };

   // first用法

   int first = numbers.first(number => number > 80);

   int first1 = numbers.first();

   console.writeline(first1);

   console.writeline(first);

9

         union是将兩個集合進行合并操作,過濾相同的項。示例代碼為:

var q = ( from c in db.customers select c.country ).union( from e in db.employeesselect e.country );

using system;

using system.collections.generic;

using system.linq;

using system.text;

namespace linq

   class student

      public string name { get; set; }

      public int age { get; set; }

      public int sex { get; set; }

      public int id { get; set; }

   class book

       public string bookname { get; set; }

       public int id { get; set; }

   class program

       static void main(string[] args)

       {

           var items = new list<student>();

           items.addrange(new student[]

           { new student{name="tom",age=20,sex=1,id=1},

             new student{name="jim",age=23,sex=1,id=2},

             new student{name="john",age=24,sex=1,id=3},

             new student{name="marry",age=22,sex=0,id=4},

             new student{name="lucy",age=21,sex=0,id=5}

           });

           var books = new list<book>();

           books.addrange(new book[]

           {

               new book{bookname="c",id=1},

               new book{bookname="c++",id=2},

               new book{bookname="c#",id=3},

               new book{bookname="word",id=1},

               new book{bookname="excel",id=1}

           // 列出所有的id 去掉重複的

           var data = (from a in items select a.id ).union (from e in books select e.id);

           foreach (var ss in data)

               console.writeline(ss);

           }

      linq有7個聚合操作符,如下表:

序号               名稱                    描述

1         aggregate     從某一特定序列或集合中收集值,當聚合完成時,它将序列中傳回值進行累積并傳回結果。

2         average       計算一個數值序列的平均值。

3         count         計算一個特定集合中元素的個數。

4                  longcount     傳回一個int64類型的值,用它來計算元素大于int32.maxvalue的集合中元素數。

5                  max           傳回一個序列中最大值。

6         min           傳回一個序列中最小值。

7                 sum                      計算集合中標明值的總和。

static void main(string[] args)

   list<int> datas = new list<int> {2,5,6,3,8,4,7,9};

   int min = datas.min();

   int max = datas.max();

   double average = datas.average();

   int count = datas.count;

   int sum = datas.sum();