您好,登錄后才能下訂單哦!
這篇文章主要介紹“Linq的基本語法概述”,在日常操作中,相信很多人在Linq的基本語法概述問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Linq的基本語法概述”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
在向大家詳細介紹Linq基本語法之前,首先讓大家了解下調(diào)用Enumberalbe擴展函數(shù),然后全面介紹Linq基本語法。
Linq基本語法
var result = from item in container orderby value ascending/descending select item;
1、獲取全部記錄
var allCars = from c in myCars select c;
2、只獲取字段名稱
var names = from c in myCars select c.PetName;
這里names就是隱式類型的變量。
3、使用Enumerable.Distinct<T>()
var makes = (from c in myCars select c.Make).Distinct<string>();
4、即可以在定義的時候調(diào)用Enumberalbe擴展函數(shù)
var names = from c in myCars select c.PetName; foreach (var n in names) { Console.WriteLine("Name: {0}", n); }
也可以在兼容的數(shù)組類型上調(diào)用
var makes = from c in myCars select c.Make; Console.WriteLine("Distinct makes:"); foreach (var m in makes.Distinct<string>()) { Console.WriteLine("Make: {0}", m); }
// Now get only the BMWs. var onlyBMWs = from c in myCars where c.Make == "BMW" select c;
// Get BMWs going at least 100 mph. var onlyFastBMWs = from c in myCars where c.Make == "BMW" && c.Speed >= 100 select c;
5、生成新的數(shù)據(jù)類型(投影)
var makesColors = from c in myCars select new {c.Make, c.Color};
6、Reverse<T>()
或者
var subset = (from c in myCars select c).Reverse<Car>(); foreach (Car c in subset) { Console.WriteLine("{0} is going {1} MPH", c.PetName, c.Speed); }
7、排序
默認是ascending
// Order all the cars by PetName. var subset = from c in myCars orderby c.PetName select c; // Now find the cars that are going less than 55 mph, // and order by descending PetName subset = from c in myCars where c.Speed > 55 orderby c.PetName descending select c;
默認順序時也可以明確指明
var subset = from c in myCars orderby c.PetName ascending select c;
8、Enumerable.Except()
兩個IEnumerable<T>兼容的對象的差集
static void GetDiff() { List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW"}; List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" }; var carDiff =(from c in myCars select c) .Except(from c2 in yourCars select c2); Console.WriteLine("Here is what you don't have, but I do:"); foreach (string s in carDiff) Console.WriteLine(s); // Prints Yugo. }
到此,關(guān)于“Linq的基本語法概述”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。