Linq擴展函數淺談
作者:佚名
這里介紹Linq擴展函數,為了使用這些Enumerable擴展函數,一般把LINQ查詢表達式用括號括起來,先轉換為IEnumerable<T>兼容的對象。
XX有很多值得學習的地方,這里我們主要介紹Linq擴展函數,包括介紹Linq擴展函數Enumerable獲取Counts等方面。
本文首先介紹Linq擴展函數(泛型函數)的方式提供的函數:
◆用不同方式產生結果集: Reverse<>(), ToArray<>(), ToList<>()
◆集合操作: Distinct<>(), Union<>(), Intersect<>()
◆統計函數: Count<>(), Sum<>(), Min<>(), Max<>()
Linq擴展函數Enumerable獲取Counts
為了使用這些Enumerable擴展函數,一般把LINQ查詢表達式用括號括起來,先轉換為IEnumerable<T>兼容的對象。
- static void GetCount()
- {
- string[] currentVideoGames = {"Morrowind", "BioShock",
- "Half Life 2: Episode 1", "The Darkness",
- "Daxter", "System Shock 2"};
- // Get count from the query.
- int numb = (from g in currentVideoGames
- where g.Length > 6
- orderby g
- select g).Count<string>();
- // numb is the value 5.
- Console.WriteLine("{0} items honor the LINQ query.", numb);
- }
定義演示的實例
- class Car
- {
- public string PetName = string.Empty;
- public string Color = string.Empty;
- public int Speed;
- public string Make = string.Empty;
- public override string ToString()
- {
- return string.Format("Make={0}, Color={1}, Speed={2}, PetName={3}",
- Make, Color, Speed, PetName);
- }
- }
- static void Main(string[] args)
- {
- Console.WriteLine("***** Fun with Query Expressions *****"n");
- // This array will be the basis of our testing
- Car[] myCars = new [] {
- new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"},
- new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"},
- new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"},
- new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"},
- new Car{ PetName = "Hank", Color = "Tan", Speed = 0, Make = "Ford"},
- new Car{ PetName = "Sven", Color = "White", Speed = 90, Make = "Ford"},
- new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"},
- new Car{ PetName = "Zippy", Color = "Yellow", Speed = 55, Make = "VW"},
- new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"}
- };
- // We will call various methods here!
- Console.ReadLine();
- }
【編輯推薦】
責任編輯:佚名
來源:
IT168