LINQ标准查询运算符的执行方式-即时
即时,声明查询的位置立即执行。查询返回如果是不可以枚举的的结果,都会立即执行。
执行方式为“”即时”的查询运算符有下面这些。
- Aggregate 应用累计器函数和结果选择器,返回传入泛型类型TSource
//找出字符串最长值 string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" }; string longestName = fruits.Aggregate("banana", (longest, next) => next.Length > longest.Length ? next : longest, fruit => fruit.ToUpper()); Console.WriteLine( "The fruit with the longest name is {0}.", longestName);
- All 判断所有函数是否满足条件,返回bool
string[] names = { "ab","abc","abcd"}; bool allStartWithab = names.All(p => p.StartsWith("ab")); bool allStartWithabc = names.All(p => p.StartsWith("abc")); Console.WriteLine( "{0} pet names start with 'ab'. {1} pet names start with 'abc'", allStartWithab ? "All" : "Not all", allStartWithabc ? "all":"not all");
- Any 判断序列是否包含元素,返回bool
List<int> numbers = new List<int> { 1, 2 }; bool hasElements = numbers.Any(); bool hasElementsEquals2 = numbers.Any(num=>num==2); Console.WriteLine($"{hasElements} {hasElementsEquals2}");
- Average 求平均值
List<int> grades = new List<int> { 78, 92, 100, 37, 81 }; var average = grades.Average(); Console.WriteLine("The average grade is {0}.", average);
- Contains 是否包含特定的元素
string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; string fruit = "mango"; bool hasMango = fruits.Contains(fruit);
- Count 计算序列的数目,返回类型Int
string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; fruits.Count();
- ElementAt 返回源序列指定位置的元素
string[] names = { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" }; Random random = new Random(DateTime.Now.Millisecond); var name = names.ElementAt(5); Console.WriteLine("The name chosen at random is '{0}'.", name);
ElementAtDefault
First
Empty
FirstDefault 返回序列的第一个元素 ,如果为空则返回类型的默认值
string[] names = { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" }; string firstLongName = names.FirstOrDefault(name => name.Length > 20); Console.WriteLine("The first long name is '{0}'.", firstLongName); string firstVeryLongName = names.FirstOrDefault(name => name.Length > 30); Console.WriteLine( "There is {0} name longer than 30 characters.", string.IsNullOrEmpty(firstVeryLongName) ? "not a" : "a"); //如果为空,希望设另一个值,可以使用DefaultIfEmpty 后面必须使用First方法. List<int> months = new List<int> { }; int firstMonth2 = months.DefaultIfEmpty(1).First(); Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2);
- Last、LastOrDefault
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 67, 12, 19 }; int last = numbers.Last(num => num > 80); int last1 = numbers.Last(); Console.WriteLine(last); Console.WriteLine(last1); int[] numbers1 = { }; Console.WriteLine(numbers1.LastOrDefault()); Console.WriteLine(numbers1.DefaultIfEmpty(9999).Last());
- LongCount
namespace ConsoleApp4 { class Program { static void Main(string[] args) { Pet[] pets = { new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 } }; const int Age = 3; int count0 = pets.Count(pet => pet.Name.StartsWith("B")); long count = pets.LongCount(pet => pet.Age > Age); long count1 = pets.LongCount(); long count2 = pets.LongLength; Console.WriteLine("There are {0} animals over age {1}.{2},{3}", count, Age,count1,count2); } } class Pet { public string Name { get; set; } public int Age { get; set; } } }
- Max
List<long> longs = new List<long> { 4294967296L, 466855135L, 81125L }; long max = longs.Max(); Console.WriteLine("The largest number is {0}.", max);
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
int min = pets.Min(pet => pet.Age+pet.Name.Length);
Console.WriteLine("The youngest animal is age {0}.", min)
- SequenceEquals 比较两个序列是否相等,使用默认比较器,也可以传一个新的比较器。返回bool值
Pet pet1 = new Pet { Name = "Turbo", Age = 2 }; Pet pet2 = new Pet { Name = "Peanut", Age = 8 }; List<Pet> pets1 = new List<Pet> { pet1, pet2 }; List<Pet> pets2 = new List<Pet> { pet1, pet2 }; bool equal = pets1.SequenceEqual(pets2); Console.WriteLine( "The lists {0} equal.", equal ? "are" : "are not"); List<Pet> pets3 = new List<Pet> { pet2, pet1 }; equal = pets1.SequenceEqual(pets3); Console.WriteLine( "The lists {0} equal.", equal ? "are" : "are not");
- Single 返回序列中特定的元素,元素不唯一和找不到元素都抛异常。
string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; string fruit1 = fruits.Single(fruit => fruit.Length >10); Console.WriteLine(fruit1); //抛异常 //string fruit2 = fruits.Single(fruit => fruit.Length >0); //抛异常 //string fruit3 = fruits.Single();
- SingleDefault 返回序列中特定的元素,元素不唯一则抛异常
int[] pageNumbers = { }; int pageNumber1 = pageNumbers.SingleOrDefault(); Console.WriteLine("The value of the pageNumber1 variable is {0}", pageNumber1); int pageNumber2 = pageNumbers.DefaultIfEmpty(1).Single(); Console.WriteLine("The value of the pageNumber2 variable is {0}", pageNumber2);
- Sum
float?[] points = { null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F }; float? sum = points.Sum(); Console.WriteLine("Total points earned: {0}", sum);
- ToArray
List<Package> packages = new List<Package> { new Package { Company = "Coho Vineyard", Weight = 25.2 }, new Package { Company = "Lucerne Publishing", Weight = 18.7 }, new Package { Company = "Wingtip Toys", Weight = 6.0 }, new Package { Company = "Adventure Works", Weight = 33.8 } }; string[] companies = packages.Select(pkg => pkg.Company).ToArray();
- ToDictionary
List<Package> packages = new List<Package> new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L }, new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L } }; Dictionary<long, Package> dictionary = packages.ToDictionary(p=>p.TrackingNumber); foreach (var kvp in dictionary) { Console.WriteLine( "Key {0}: {1}, {2} pounds", kvp.Key, kvp.Value.Company, kvp.Value.Weight); }
- ToList
string[] fruits = { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; List<int> lengths = fruits.Select(fruit => fruit.Length).ToList(); foreach (int length in lengths) { Console.WriteLine(length); }
量变会引起质变。