至于linq是什么之類的已經有過太多的文章介紹,亦不清楚的胡朋友可以自己搜索一下便可以得到大量的答案
為了體驗linq究竟能帶給我們什么體驗,我們直接從代碼入手:
string[] Words = new string[] { "test","test1","linqtosql","linqtoobject","beautiful"};
var result = from p in words where p.Length > 5 select p; Console.WriteLine(result.GetType()); foreach (var item in result) { Console.WriteLine(item); } Console.Read();
以上代碼即為實現從一個數組中獲取長度大于5的集合,linq返回的結果類型可以result.GetType()進行查看,回想一下在沒有linq之前我們如果要實現相同的功能的話需要如何實現,是否是需要這樣做呢:
foreach(var item in words)
{
if (item.length>5)
console.writeline(item);
}
從以上這兩段簡單代碼上比較似乎linq并沒有帶給我們什么神奇胡內容,但是我們接著往下看。
string[] words = new string[] { "test","tes1","linqtosql","linqtoobject","beautiful"}; var result = from p in words orderby p descending group p by p.Length into tempqroup orderby tempqroup.Key descending select new { length=tempqroup.Key, words=tempqroup }; foreach (var item in result) { foreach (var p in item.words) { Console.WriteLine(p); } } Console.Read();
以上我們則是實現一個對數組內容按單詞長度分組的一個功能,如果我們要使用傳統的代碼實現 的話會發現將不得不去寫很多的代碼,對嗎?
好了linq的開胃菜到此結束,后面linq胡更多的應用將展開。
新聞熱點
疑難解答