1. 程式人生 > >C# Linq基本操作以及into、let關鍵字

C# Linq基本操作以及into、let關鍵字

概念:“查詢”也是一種指令,使用這組指令可以從給定的一個或多個數據源中檢索資料,並以指令的形式返回結果。Linq也是一種查詢,可以為程式語言提供強大的方便的查詢功能,並與其合為一體。

Linq的強大體現在它的簡潔 方便的程式碼量。比如要篩選出list中一個屬性的元素,相對於list就要遍歷判斷;但是你用linq就只需要一句。但是這也會造成一些問題,導致後期比人維護你的專案造成麻煩(哪有最好的東西呀,雙刃劍吧 哈哈)

 

From:子句被查詢的資料來源(相當於for迴圈)

Where:子句指定元素所滿足的過濾條件(相當於if判斷)

orderby:表現方式(相當於排序方式,升序、降序。。。)

Select:子句制定查詢結果的表現形式,(相當於return)

 

下面用程式碼來說明問題:

// Linq  Query語句

int[] numbers = { 12, 23, 34, 45, 56, 67 };
            var numQuery = from num in numbers
                           where num % 2 == 0
                           orderby num ascending // ascending 升序(可省略)
                           select num;
            foreach(var n in numQuery)
            {
                Console.WriteLine(n);
            }

// Linq Method語句

var numMethod = numbers.Where(n => n % 2 == 0).OrderBy(n => n);
            foreach(var n in numMethod)
            {
                Console.WriteLine(n);
            }

注意:以上兩個語句的程式碼量相差還是有點大的,Query將每塊邏輯分開,而Method將所有邏輯集中於一行來實現。

 

into、let關鍵字

// Linq  into關鍵字

List<Peo> peoList = new List<Peo>();
            peoList.Add(new Peo() { name = "lizhi", city = "shanghai" });
            peoList.Add(new Peo() { name = "linqingxia", city = "beijing" });
            peoList.Add(new Peo() { name = "liuyifei", city = "shanghai" });
            var intoLinq = from num in peoList
                           group num by num.city into groupnum
                           where groupnum.Count() >= 2
                           select new { city = groupnum.Key, number = groupnum.Count() };
            foreach(var i in intoLinq)
            {
                Console.WriteLine(i.city + "---" + i.number);
            }

以上示例:into 字面解釋意為“打入”,以上事例將遍歷proList得到的num篩選出city屬性放入groupnum中,這裡的groupnam可以看作是一個集合,這個集合存的是city屬性。

// Linq  let關鍵字

string[] strings = { "hello world.", "lin qing xia", "wang zu xian" };
            var strs = from s in strings
                       let words = s.Split(' ')
                       from word in words
                       let w = word.ToUpper()
                       select w;
            foreach(var s in strs)
            {
                Console.WriteLine(s);
            }

以上示例:將遍歷的元素進行處理,並將處理結果存放到words,這裡的words也可看作一個集合(可以這樣理解,具體自己去發掘 嘿嘿)

 

注意:Linq雖然方便,但是並不是適用於所有的條件篩選或者排序。比如揹包、商城的根據什麼什麼排序之類的了。有一些專案會明顯指出不可用linq進行排序。貌似是引用底層涉及到太多的拆裝箱操作吧 貌似(樓主也是小菜一枚,歡迎改正)