C#之Linq入门首选案例

编程入门 行业动态 更新时间:2024-10-03 21:20:43

C#之Linq<a href=https://www.elefans.com/category/jswz/34/1770026.html style=入门首选案例"/>

C#之Linq入门首选案例

        此文章对Linq不会有过多的解释,只用代码呈现Linq的用法!

       查看注意事项:

                            ①:命名空间与方法名基本一致,如:All方法的用法,命名空间为All;

                            ②:如:命名空间为GroupBy_02,说明GroupBy方法有多个例子;

                            ③:用例使用了字典排序,方便大家查找!

All用法:

namespace All
{class Program{static void Main(string[] args){AllEx2();}class Pet{public string Name { get; set; }public int Age { get; set; }}class Person{public string LastName { get; set; }public Pet[] Pets { get; set; }}public static void AllEx2(){List<Person> people = new List<Person>{ new Person { LastName = "Haas",Pets = new Pet[] { new Pet { Name="Barley", Age=10 },new Pet { Name="Boots", Age=14 },new Pet { Name="Whiskers", Age=6 }}},new Person { LastName = "Fakhouri",Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}},new Person { LastName = "Antebi",Pets = new Pet[] { new Pet { Name = "Belle", Age = 8} }},new Person { LastName = "Philips",Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2},new Pet { Name = "Rover", Age = 13}} }};// Determine which people have pets that are all older than 5.//确定哪些人有5岁以上的宠物:IEnumerable<string> names = from person in peoplewhere person.Pets.All(pet => pet.Age > 5)select person.LastName;foreach (string name in names){Console.WriteLine(name);}/* This code produces the following output:* 此代码输出如下:* Haas* Antebi*/}}
}

 Any用法:

namespace Any
{class Program{static void Main(string[] args){//Any()方法 确定序列是否包含任何元素。List<int> numbers = new List<int> { 1, 2 };bool hasElements = numbers.Any();Console.WriteLine("The list {0} empty.",hasElements ? "is not" : "is");}}
}

Cast用法:

namespace Cast
{class Program{static void Main(string[] args){ArrayList fruits = new ArrayList();fruits.Add("mango");fruits.Add("apple");fruits.Add("lemon");IEnumerable<string> query =fruits.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit);// The following code, without the cast, doesn't compile.下面的代码没有编译,也不会有编译//IEnumerable<string> query1 =//    fruits.OrderBy(fruit => fruit).Select(fruit => fruit);foreach (string fruit in query){Console.WriteLine(fruit);}// This code produces the following output: //此代码生成以下输出// apple // lemon// mango}}
}

Concat用法:

namespace Concat
{class Program{/// <summary>/// Concat连接两个字符串/// </summary>/// <param name="args"></param>static void Main(string[] args){ConcatEx1();}class Pet{public string Name { get; set; }public int Age { get; set; }}static Pet[] GetCats(){Pet[] cats = { new Pet { Name="Barley", Age=8 },new Pet { Name="Boots", Age=4 },new Pet { Name="Whiskers", Age=1 } };return cats;}static Pet[] GetDogs(){Pet[] dogs = { new Pet { Name="Bounder", Age=3 },new Pet { Name="Snoopy", Age=14 },new Pet { Name="Fido", Age=9 } };return dogs;}public static void ConcatEx1(){Pet[] cats = GetCats();Pet[] dogs = GetDogs();/*下面的代码示例演示如何使用concat <来源>(IEnumerable <来源>,IEnumerable <来源>)连接两个序列。*///IEnumerable<string> query =//    cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));/*另一种方法是将两个序列构建的集合,例如一个数组,序列,* 然后应用SelectMany方法,通过标识选择器函数。下面的示* 例演示如何使用SelectMany。*/IEnumerable<int> query =new[] { cats.Select(cat => cat.Age), dogs.Select(dog => dog.Age) }.SelectMany(name => name);foreach (int name in query){Console.WriteLine(name);}}// This code produces the following output://此代码生成以下输出// Barley// Boots// Whiskers// Bounder// Snoopy// Fido}
}

Contains用法:

namespace Contains
{class Program{/// <summary>/// 确定序列是否包含指定元素/// </summary>/// <param name="args"></param>static void Main(string[] args){string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" };string fruit = "mango";bool hasMango = fruits.Contains(fruit);Console.WriteLine("The array {0} contain '{1}'.",hasMango ? "does" : "does not",fruit);// This code produces the following output://此代码生成以下输出// The array does contain 'mango'. }}
}
namespace Contains_01
{class Program{/// <summary>/// 下面的示例演示如何实现一个相等比较器可用Contains于方法。/// </summary>/// <param name="args"></param>static void Main(string[] args){Product[] fruits = { new Product { Name = "apple", Code = 9 },new Product { Name = "orange", Code = 4 },new Product { Name = "lemon", Code = 12 } };Product apple = new Product { Name = "apple", Code = 9 };Product kiwi = new Product { Name = "kiwi", Code = 8 };ProductComparer prodc = new ProductComparer();bool hasApple = fruits.Contains(apple, prodc);bool hasKiwi = fruits.Contains(kiwi, prodc);Console.WriteLine("Apple? " + hasApple);Console.WriteLine("Kiwi? " + hasKiwi);/*This code produces the following output:Apple? TrueKiwi? False*/}public class Product{public string Name { get; set; }public int Code { get; set; }}// Custom comparer for the Product class//对Product的自定义比较器class ProductComparer : IEqualityComparer<Product>{// Products are equal if their names and product numbers are equal.//如果Products中的name和Products中Code相等,Products是平等的。public bool Equals(Product x, Product y){//Check whether the compared objects reference the same data.//检查比较对象是否引用相同的数据。if (Object.ReferenceEquals(x, y)) return true;//Check whether any of the compared objects is null.//检查任何比较对象是否为null。if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))return false;//Check whether the products' properties are equal.//检查products的属性是否相等return x.Code == y.Code && x.Name == y.Name;}// If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects.public int GetHashCode(Product product){//Check whether the object is null//检查对象是否为nullif (Object.ReferenceEquals(product, null)) return 0;//Get hash code for the Name field if it is not null.//如果 code和name不为空,就获取int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();//Get hash code for the Code field.//获取Codeint hashProductCode = product.Code.GetHashCode();//Calculate the hash code for the product.//计算product的codereturn hashProductName ^ hashProductCode;}}}
}

DefaultIfEmpty用法:

namespace DefaultIfEmpty
{class Program{/// <summary>/// 返回一个IEnumerable <T>的元素,或默认值的单点采集如果序列是空的。/// </summary>/// <param name="args"></param>static void Main(string[] args){DefaultIfEmptyEx2();}class Pet{public string Name { get; set; }public int Age { get; set; }}/*下面的代码示例演示如何使用DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)方法和指定默认值。第一个序列不是空的,第二个序列是空的。*/public static void DefaultIfEmptyEx2(){Pet defaultPet = new Pet { Name = "Default Pet", Age = 0 };List<Pet> pets1 =new List<Pet>{ new Pet { Name="Barley", Age=8 },new Pet { Name="Boots", Age=4 },new Pet { Name="Whiskers", Age=1 } };foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet)){Console.WriteLine("Name: {0}", pet.Name);}List<Pet> pets2 = new List<Pet>();foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet)){Console.WriteLine("Name: {0}", pet.Name);}}/*This code produces the following output:此代码生成以下输出Name: BarleyName: BootsName: WhiskersName: Default Pet*/}
}
namespace DefaultIfEmpty_01
{class Program{static void Main(string[] args){/*这个例子使用了一个非空序列。*/DefaultIfEmptyEx1();/*此示例使用空序列。*/List<int> numbers = new List<int>();foreach (int number in numbers.DefaultIfEmpty()){Console.WriteLine(number);}/*This code produces the following output:0*/}class Pet{public string Name { get; set; }public int Age { get; set; }}/*下面的代码示例演示如何使用DefaultIfEmpty<TSource>(IEnumerable<TSource>)提供一个默认值的情况下,源序列是空的。*/public static void DefaultIfEmptyEx1(){List<Pet> pets =new List<Pet>{ new Pet { Name="Barley", Age=8 },new Pet { Name="Boots", Age=4 },new Pet { Name="Whiskers", Age=1 } };foreach (Pet pet in pets.DefaultIfEmpty()){Console.WriteLine(pet.Name);}}/*This code produces the following output:BarleyBootsWhiskers*/}
}

Distinct用法:

namespace Distinct
{class Program{/// <summary>/// Distinct 从序列中返回不同的元素/// 下面的代码示例演示如何使用Distinct<TSource>(IEnumerable<TSource>)返回一个整数序列不同的元素。/// </summary>/// <param name="args"></param>static void Main(string[] args){List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };IEnumerable<int> distinctAges = ages.Distinct();Console.WriteLine("Distinct ages:");foreach (int age in distinctAges){Console.WriteLine(age);}/*This code produces the following output:此代码生成以下输出:Distinct ages:21465517*/}}
}
namespace Distinct_01
{class Program{/// <summary>/// 如果你想返回从一些自定义数据类型的对象序列不同的元素,/// 你必须在类中实现iequatable <T>通用接口。/// 下面的代码示例演示如何在自定义数据类型实现这个接口,/// 提供GetHashCode和equals方法。/// </summary>/// <param name="args"></param>static void Main(string[] args){Product[] products = { new Product { Name = "apple", Code = 9 },new Product { Name = "orange", Code = 4 },new Product { Name = "apple", Code = 9 },new Product { Name = "lemon", Code = 12 } };//Exclude duplicates.IEnumerable<Product> noduplicates =products.Distinct();foreach (var product in noduplicates)Console.WriteLine(product.Name + " " + product.Code);/*This code produces the following output:apple 9 orange 4lemon 12*/}public class Product : IEquatable<Product>{public string Name { get; set; }public int Code { get; set; }public bool Equals(Product other){//Check whether the compared object is null. if (Object.ReferenceEquals(other, null)) return false;//Check whether the compared object references the same data. if (Object.ReferenceEquals(this, other)) return true;//Check whether the products' properties are equal. return Code.Equals(other.Code) && Name.Equals(other.Name);}// If Equals() returns true for a pair of objects  // then GetHashCode() must return the same value for these objects. public override int GetHashCode(){//Get hash code for the Name field if it is not null. int hashProductName = Name == null ? 0 : Name.GetHashCode();//Get hash code for the Code field. int hashProductCode = Code.GetHashCode();//Calculate the hash code for the product. return hashProductName ^ hashProductCode;}}}
}
namespace Distinct_02
{class Program{/// <summary>/// 下面的示例演示如何实现一个相等比较器,可用于Distinct的方法。/// </summary>/// <param name="args"></param>static void Main(string[] args){Product[] products = { new Product { Name = "apple", Code = 9 },new Product { Name = "orange", Code = 4 },new Product { Name = "apple", Code = 9 },new Product { Name = "lemon", Code = 12 } };//Exclude duplicates.IEnumerable<Product> noduplicates =products.Distinct(new ProductComparer());foreach (var product in noduplicates)Console.WriteLine(product.Name + " " + product.Code);/*This code produces the following output:apple 9 orange 4lemon 12*/}public class Product{public string Name { get; set; }public int Code { get; set; }}// Custom comparer for the Product classclass ProductComparer : IEqualityComparer<Product>{// Products are equal if their names and product numbers are equal.public bool Equals(Product x, Product y){//Check whether the compared objects reference the same data.if (Object.ReferenceEquals(x, y)) return true;//Check whether any of the compared objects is null.if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))return false;//Check whether the products' properties are equal.return x.Code == y.Code && x.Name == y.Name;}// If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects.public int GetHashCode(Product product){//Check whether the object is nullif (Object.ReferenceEquals(product, null)) return 0;//Get hash code for the Name field if it is not null.int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();//Get hash code for the Code field.int hashProductCode = product.Code.GetHashCode();//Calculate the hash code for the product.return hashProductName ^ hashProductCode;}}}
}

ElementAt用法:

namespace ElementAt
{class Program{/// <summary>/// ElementAt按顺序返回指定索引处的元素/// 下面的代码示例演示如何使用ElementAt返回在特定位置的元素。/// </summary>/// <param name="args"></param>static void Main(string[] args){string[] names ={ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow","Hedlund, Magnus", "Ito, Shu" };Random random = new Random(DateTime.Now.Millisecond);string name = names.ElementAt(random.Next(0, names.Length));//The name chosen at random is 随机选择的名字是Console.WriteLine("The name chosen at random is '{0}'.", name);/*This code produces the following sample output:此代码生成以下输出:The name chosen at random is 'Ito, Shu'.*/}}
}
namespace ElementAtOrDefault
{class Program{/// <summary>/// ElementAtOrDefault如果索引超出范围,则返回序列中指定索引的元素或默认值。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用*  ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32)。* 这个例子使用了索引的值,该值超出了源序列的边界。*/string[] names = { "Hartono, Tommy", "Adams, Terry","Andersen, Henriette Thaulow","Hedlund, Magnus", "Ito, Shu" };int index = 20;string name = names.AsQueryable().ElementAtOrDefault(index);Console.WriteLine("The name chosen at index {0} is '{1}'.",index,String.IsNullOrEmpty(name) ? "[NONE AT THIS INDEX]" : name);/*This code produces the following output:The name chosen at index 20 is '[NONE AT THIS INDEX]'.*/}}
}

Except用法:

namespace Except
{class Program{/// <summary>/// Except除了/// Produces the set difference of two sequences.产生两个序列之间的集合差/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用* Except<TSource>(IQueryable<TSource>, IEnumerable<TSource>)* 这些元素只出现在第一源序列。*/double[] numbers1 = { 1,2,3,4,5};double[] numbers2 = { 2};// Get the numbers from the first array that// are NOT in the second array.//从第一组中获取不在第二数组中的数字IEnumerable<double> onlyInFirstSet =numbers1.AsQueryable().Except(numbers2);foreach (double number in onlyInFirstSet)Console.WriteLine(number);/*This code produces the following output:此代码生成以下输出              1345*/}}
}

First用法:

namespace First_01
{class Program{/// <summary>/// First 第一/// Returns the first element of a sequence.返回序列中的第一个元素/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用First<TSource>(IQueryable<TSource>) 返回序列中的第一个元素。*/int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,83, 23, 87, 435, 67, 12, 19 };int first = numbers.AsQueryable().First();Console.WriteLine(first);/*This code produces the following output:此代码生成以下输出9*/}}
}
namespace First_02
{class Program{static void Main(string[] args){/*下面的代码示例演示如何使用* First<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) * 返回序列中满足条件的第一个元素。*/int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,83, 23, 87, 435, 67, 12, 19 };// Get the first number in the array that is greater than 80.//获取数组中第一个大于80的数字int first = numbers.AsQueryable().First(number => number > 80);Console.WriteLine(first);/*This code produces the following output:92*/}}
}

FirstOrDefault用法:

namespace FirstOrDefault_01
{class Program{/// <summary>/// FirstOrDefault 第一或者默认/// Returns the first element of a sequence, or a default value if no element is found./// 返回序列的第一个元素,如果没有元素,则返回默认值。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用FirstOrDefault<TSource>(IQueryable<TSource>)在一个空的序列。*/// Create an empty array.创建一个空数组int[] numbers = { };// Get the first item in the array, or else the // default value for type int (0).//获取数组中的第一个,或其他是int类型的默认值int first = numbers.AsQueryable().FirstOrDefault();Console.WriteLine(first);/*This code produces the following output:此代码生成以下输出0*/}}
}
namespace FirstOrDefault_02
{class Program{static void Main(string[] args){/*有时default(TSource)是不是要使用集合是否包含任何元素的默认值。* 而不是检查不必要的默认值的结果,然后改变它如果有必要,你可以* 使用 DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) * 来指定您想要使用如果集合是空的默认值的方法。然后,*  First<TSource>(IQueryable<TSource>)获得的第一个元素。* 下面的代码示例使用这两种技术获得一个默认值为1,* 如果数字月份的集合是空的。因为整数的默认值是0,* 它与每个月份不对应,所以默认值必须指定为1。在查询完成后,* 检查第一个结果变量以获取不需要的默认值。第二个结果变量被* 调用DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource)* 指定默认值1。*/List<int> months = new List<int> {};// Setting the default value to 1 after the query.//查询后将默认值设置为1int firstMonth1 = months.AsQueryable().FirstOrDefault();if (firstMonth1 == 0){firstMonth1 = 1;}Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1);// Setting the default value to 1 by using DefaultIfEmpty() in the query.//设置默认值为1,用 DefaultIfEmpty()查询。int firstMonth2 = months.AsQueryable().DefaultIfEmpty(1).First();Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2);/*This code produces the following output:The value of the firstMonth1 variable is 1The value of the firstMonth2 variable is 1*/}}
}

GroupBy用法:

namespace GroupBy_01
{class Program{/// <summary>/// GroupBy分组/// Groups the elements of a sequence.分组序列中的元素/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用* GroupBy<TSource,TKey,TElement,TResult>(IQueryable<TSource>,* Expression<Func<TSource,TKey>>,* Expression<Func<TSource,TElement>>,* Expression<Func<TKey,IEnumerable<TElement>,TResult>>) * 组的元素一个序列和项目序列的TResult型结果。*/GroupByEx4();}class Pet{public string Name { get; set; }public double Age { get; set; }}public static void GroupByEx4(){// Create a list of pets.//创建一个宠物集合List<Pet> petsList =new List<Pet>{ new Pet { Name="Barley", Age=8.3 },new Pet { Name="Boots", Age=4.9 },new Pet { Name="Whiskers", Age=1.5 },new Pet { Name="Daisy", Age=4.3 } };// Group Pet.Age values by the Math.Floor of the age.按年龄分组计算宠物年龄值。// Then project an anonymous type from each group然后从每个组投射匿名类型// that consists of the key, the count of the group's这包括密钥,组的计数// elements, and the minimum and maximum age in the group.元素和组中的最小和最大年龄。var query = petsList.AsQueryable().GroupBy(pet =>Math.Floor(pet.Age),pet => pet.Age,(baseAge, ages) => new{Key = baseAge,Count = ages.Count(),Min = ages.Min(),Max = ages.Max()});   // Iterate over each anonymous type.迭代每个匿名类型foreach (var result in query){Console.WriteLine("\nAge group: " + result.Key);Console.WriteLine("Number of pets in this age group: " + result.Count);Console.WriteLine("Minimum age: " + result.Min);Console.WriteLine("Maximum age: " + result.Max);}/*  This code produces the following output:Age group: 8Number of pets in this age group: 1Minimum age: 8.3Maximum age: 8.3Age group: 4Number of pets in this age group: 2Minimum age: 4.3Maximum age: 4.9Age group: 1Number of pets in this age group: 1Minimum age: 1.5Maximum age: 1.5*/}}
}

namespace GroupBy_02
{class Program{static void Main(string[] args){/*下面的代码示例演示如何使用GroupBy<TSource,TKey,TElement>(IQueryable<TSource>,* Expression<Func<TSource,TKey>>, Expression<Func<TSource,TElement>>)组的序列中的元素。*/GroupByEx2();}class Pet{public string Name { get; set; }public string Type { get; set; }public int Age { get; set; }}public static void GroupByEx2(){// Create a list of Pet objects.//创建宠物对象列表List<Pet> pets =new List<Pet>{ new Pet { Name="Barley", Age=8},new Pet { Name="Boots", Age=4},new Pet { Name="Whiskers", Age=1},new Pet { Name="Daisy", Age=4 } };// Group the pets using Pet.Age as the key.// Use Pet.Name as the value for each entry.IEnumerable<IGrouping<int, string>> query =pets.AsQueryable().GroupBy(pet => pet.Age, pet => pet.Name);// Iterate over each IGrouping in the collection.foreach (IGrouping<int, string> petGroup in query){// Print the key value of the IGrouping.Console.WriteLine(petGroup.Key);// Iterate over each value in the // IGrouping and print the value.foreach (string name in petGroup)Console.WriteLine("  {0}", name);}}/*This code produces the following output:8Barley4BootsDaisy1Whiskers*/}
}

namespace GroupBy_03
{class Program{static void Main(string[] args){GroupByEx3();}class Pet{public string Name { get; set; }public double Age { get; set; }}public static void GroupByEx3(){// Create a list of pets.创建宠物列表List<Pet> petsList =new List<Pet>{ new Pet { Name="Barley", Age=8.3 },new Pet { Name="Boots", Age=4.9 },new Pet { Name="Whiskers", Age=1.5 },new Pet { Name="Daisy", Age=4.3 } };// Group Pet objects by the Math.Floor of their age.// Then project an anonymous type from each group// that consists of the key, the count of the group's// elements, and the minimum and maximum age in the group./*按年龄和年龄分组宠物对象。然后从每个组投射匿名类型包括键,组的计数元素,以及组中的最小和最大年龄。*/var query = petsList.AsQueryable().GroupBy(pet => Math.Floor(pet.Age),(age, pets) => new{Key = age,Count = pets.Count(),Min = pets.Min(pet => pet.Age),Max = pets.Max(pet => pet.Age)});// Iterate over each anonymous type.迭代每个匿名类型。foreach (var result in query){Console.WriteLine("\nAge group: " + result.Key);Console.WriteLine("Number of pets in this age group: " + result.Count);Console.WriteLine("Minimum age: " + result.Min);Console.WriteLine("Maximum age: " + result.Max);}/*  This code produces the following output:Age group: 8Number of pets in this age group: 1Minimum age: 8.3Maximum age: 8.3Age group: 4Number of pets in this age group: 2Minimum age: 4.3Maximum age: 4.9Age group: 1Number of pets in this age group: 1Minimum age: 1.5Maximum age: 1.5*/}}
}

namespace GroupBy_04
{class Program{static void Main(string[] args){GroupByEx1();}class Pet{public string Name { get; set; }public int Age { get; set; }}public static void GroupByEx1(){// Create a list of Pet objects.List<Pet> pets =new List<Pet>{ new Pet { Name="Barley", Age=8 },new Pet { Name="Boots", Age=4 },new Pet { Name="Whiskers", Age=1 },new Pet { Name="Daisy", Age=4 } };// Group the pets using Pet.Age as the key.// Use Pet.Name as the value for each entry.var query = pets.AsQueryable().GroupBy(pet => pet.Age);// Iterate over each IGrouping in the collection.foreach (var ageGroup in query){Console.WriteLine("Age group: {0}  Number of pets: {1}", ageGroup.Key, ageGroup.Count());}}/*This code produces the following output:Age group: 8  Number of pets: 1Age group: 4  Number of pets: 2Age group: 1  Number of pets: 1*/}
}

GroupJoin用法:

namespace GroupJoin
{class Program{/// <summary>/// GuoupJoin 联合分组/// Correlates the elements of two sequences based on key equality and groups the results./// 基于键相等将两个序列的元素关联起来并分组结果。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用群组加入* GroupJoin<TOuter,TInner,TKey,TResult>(IQueryable<TOuter>,* IEnumerable<TInner>, Expression<Func<TOuter,TKey>>,* Expression<Func<TInner,TKey>>, * Expression<Func<TOuter,IEnumerable<TInner>,TResult>>) * 对两个序列进行分组加入。*/GroupJoinEx1();}class Person{public string Name { get; set; }}class Pet{public string Name { get; set; }public Person Owner { get; set; }}public static void GroupJoinEx1(){Person magnus = new Person { Name = "Hedlund, Magnus" };Person terry = new Person { Name = "Adams, Terry" };Person charlotte = new Person { Name = "Weiss, Charlotte" };Pet barley = new Pet { Name = "Barley", Owner = terry };Pet boots = new Pet { Name = "Boots", Owner = terry };Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };Pet daisy = new Pet { Name = "Daisy", Owner = magnus };List<Person> people = new List<Person> { magnus, terry, charlotte };List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };// Create a list where each element is an anonymous // type that contains a person's name and a collection // of names of the pets that are owned by them./*创建一个列表,其中每个元素是匿名的包含一个人姓名和一个集合的类型[或]它们所拥有的宠物的名称。*/var query =people.AsQueryable().GroupJoin(pets,person => person,pet => pet.Owner,(person, petCollection) =>new{OwnerName = person.Name,Pets = petCollection.Select(pet => pet.Name)});foreach (var obj in query){// Output the owner's name.Console.WriteLine("{0}:", obj.OwnerName);// Output each of the owner's pet's names.foreach (string pet in obj.Pets)Console.WriteLine("  {0}", pet);}}/*This code produces the following output:Hedlund, Magnus:DaisyAdams, Terry:BarleyBootsWeiss, Charlotte:Whiskers*/}
}

Intersect用法:

namespace Intersect
{class Program{/// <summary>/// Intersect交集/// Produces the set intersection of two sequences./// 产生两个序列集合之间的交集/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用Intersect<TSource>(IQueryable<TSource>, IEnumerable<TSource>) 每两序列出现的元素。*/int[] id1 = { 44, 26, 92, 30, 71, 38 };int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };// Get the numbers that occur in both arrays (id1 and id2).IEnumerable<int> both = id1.AsQueryable().Intersect(id2);foreach (int id in both)Console.WriteLine(id);/*This code produces the following output:2630*/}}
}

Join用法:

namespace Join
{class Program{/// <summary>/// Join连接/// Correlates the elements of two sequences based on matching keys./// 基于匹配键关联两个序列的元素。/// </summary>/// <param name="args"></param>static void Main(string[] args){JoinEx1();}class Person{public string Name { get; set; }}class Pet{public string Name { get; set; }public Person Owner { get; set; }}public static void JoinEx1(){Person magnus = new Person { Name = "Hedlund, Magnus" };Person terry = new Person { Name = "Adams, Terry" };Person charlotte = new Person { Name = "Weiss, Charlotte" };Pet barley = new Pet { Name = "Barley", Owner = terry };Pet boots = new Pet { Name = "Boots", Owner = terry };Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };Pet daisy = new Pet { Name = "Daisy", Owner = magnus };List<Person> people = new List<Person> { magnus, terry, charlotte };List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };// Join the list of Person objects and the list of Pet objects // to create a list of person-pet pairs where each element is // an anonymous type that contains the name of pet and the name// of the person that owns the pet.var query = people.AsQueryable().Join(pets,person => person,pet => pet.Owner,(person, pet) =>new { OwnerName = person.Name, Pet = pet.Name });foreach (var obj in query){Console.WriteLine("{0} - {1}",obj.OwnerName,obj.Pet);}}/*This code produces the following output:Hedlund, Magnus - DaisyAdams, Terry - BarleyAdams, Terry - BootsWeiss, Charlotte - Whiskers*/}
}

Last用法:

namespace Last
{class Program{/// <summary>/// Last最后一个/// Returns the last element in a sequence./// 返回序列中最后一个元素/// </summary>/// <param name="args"></param>static void Main(string[] args){int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,83, 23, 81, 67, 12, 19 };// Get the last number in the array that is greater than 80.//获取数组中大于80的最后一个数字int last = numbers.AsQueryable().Last(num => num > 80);Console.WriteLine(last);/*This code produces the following output:此代码生成以下输出81*/}}
}

LastOrDefault用法:

namespace LastOrDefault
{class Program{static void Main(string[] args){// Create an empty array.创建一个空数组string[] fruits = { };// Get the last item in the array, or else the default// value for type string (null)./*获取数组中的最后一项,或者字符串类型的默认值(null)*/string last = fruits.AsQueryable().LastOrDefault();Console.WriteLine(String.IsNullOrEmpty(last) ? "[STRING IS NULL OR EMPTY]" : last);/*This code produces the following output:[STRING IS NULL OR EMPTY]*/List<int> daysOfMonth = new List<int> {};// Setting the default value to 1 after the query.//查询后设置默认值为1int lastDay1 = daysOfMonth.AsQueryable().LastOrDefault();if (lastDay1 == 0){lastDay1 = 1;}Console.WriteLine("The value of the lastDay1 variable is {0}", lastDay1);// Setting the default value to 1 by using DefaultIfEmpty() in the query.//设置默认值为1,用DefaultIfEmpty()查询int lastDay2 = daysOfMonth.AsQueryable().DefaultIfEmpty(1).Last();Console.WriteLine("The value of the lastDay2 variable is {0}", lastDay2);/*This code produces the following output:The value of the lastDay1 variable is 1The value of the lastDay2 variable is 1*/}}
}

LongCount用法:

namespace LongCount_01
{class Program{/// <summary>/// LongCount 长计数/// Returns an Int64 that represents the number of elements in sequence./// 返回一个长整型表示序列中的元素的数目。/// </summary>/// <param name="args"></param>static void Main(string[] args){/** 下面的代码示例演示如何使用LongCount<TSource>(IQueryable<TSource>)计算数组中的元素。*/string[] fruits = { "apple", "banana", "mango","orange", "passionfruit", "grape" };long count = fruits.AsQueryable().LongCount();Console.WriteLine("There are {0} fruits in the collection.", count);/*This code produces the following output:There are 6 fruits in the collection.*/}}
}
namespace LongCount_02
{class Program{static void Main(string[] args){/*下面的代码示例演示如何使用*LongCount<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) * 计算数组中满足条件的元素。*/LongCountEx2();}class Pet{public string Name { get; set; }public int Age { get; set; }}public static void LongCountEx2(){Pet[] pets = { new Pet { Name="Barley", Age=8 },new Pet { Name="Boots", Age=4 },new Pet { Name="Whiskers", Age=1 } };const int Age = 3;// Count the number of Pet objects where Pet.Age is greater than 3.//统计宠物年龄大于3岁的宠物的数量long count = pets.AsQueryable().LongCount(pet => pet.Age > Age);Console.WriteLine("There are {0} animals over age {1}.", count, Age);}/*This code produces the following output:此代码生成以下输出There are 2 animals over age 3.三岁以上的动物有两只*/}
}

Max用法:

namespace Max
{class Program{/// <summary>/// Max 最大/// The maximum value in the sequence./// 序列中最大的值/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用Max<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,TResult>>)确定在一个序列的投影值的最大值。*/MaxEx2();/*下面的代码示例演示如何使用Max<TSource>(IQueryable<TSource>)确定在一个序列中的最大值。*/List<long> longs = new List<long> { 4294967296L, 466855135L, 81125L };long max = longs.AsQueryable().Max();Console.WriteLine("The largest number is {0}.", max);/*This code produces the following output:The largest number is 4294967296.*/}class Pet{public string Name { get; set; }public int Age { get; set; }}public static void MaxEx2(){Pet[] pets = { new Pet { Name="Barley", Age=8 },new Pet { Name="Boots", Age=4 },new Pet { Name="Whiskers", Age=1 } };// Add Pet.Age to the length of Pet.Name// to determine the "maximum" Pet object in the array.//宠物的年龄加上宠物名字的长度,确定序列中"maximum"的宠物对象int max =pets.AsQueryable().Max(pet => pet.Age + pet.Name.Length);Console.WriteLine("The maximum pet age plus name length is {0}.",max);}/*This code produces the following output:此代码生成以下输出The maximum pet age plus name length is 14.*/}
}

Min用法:

namespace Min
{class Program{/// <summary>/// Min 最小/// The minimum value in the sequence./// 序列中的最小值/// </summary>/// <param name="args"></param>static void Main(string[] args){MinEx2();}class Pet{public string Name { get; set; }public int Age { get; set; }}public static void MinEx2(){/*下面的代码示例演示如何使用* Min<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,TResult>>)* 确定在一个序列的投影值的最小值。*/Pet[] pets = { new Pet { Name="Barley", Age=8 },new Pet { Name="Boots", Age=4 },new Pet { Name="Whiskers", Age=1 } };// Get the Pet object that has the smallest Age value.//获取具有最小年龄值得宠物对象int min = pets.AsQueryable().Min(pet => pet.Age);Console.WriteLine("The youngest animal is age {0}.", min);/*下面的代码示例演示如何使用 Min<TSource>(IQueryable<TSource>) 确定序列中的最小值。*/double[] doubles = { 1.5E+104, 9E+103, -2E+103 };double min1 = doubles.AsQueryable().Min();Console.WriteLine("The smallest number is {0}.", min1);/*This code produces the following output:The smallest number is -2E+103.*/}/*This code produces the following output:The youngest animal is age 1.  */}
}

OfType用法:

namespace OfType
{class Program{/// <summary>/// OfType 类型/// Filters the elements of an IQueryable based on a specified type./// 过滤器基于指定的类型的一个IQueryable的元素/// 过滤一个基于指定类型的IQueryable的元素?/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用OfTypel类型PropertyInfo列表中的元素的类型的MemberInfo。*/// Create a list of MemberInfo objects.  创建MemberInfo对象列表List<MemberInfo> members = typeof(String).GetMembers().ToList();// Return only those items that can be cast to type PropertyInfo.//只返回那些可以强制转换为类型PropertyInfo项目。IQueryable<PropertyInfo> propertiesOnly =members.AsQueryable().OfType<PropertyInfo>();Console.WriteLine("Members of type 'PropertyInfo' are:");foreach (PropertyInfo pi in propertiesOnly)Console.WriteLine(pi.Name);/*This code produces the following output:Members of type 'PropertyInfo' are:CharsLength*/}}
}

OrderBy用法:

namespace OrderBy
{class Program{/// <summary>/// OrderBy排序/// Sorts the elements of a sequence in ascending order./// 按升序对序列元素进行排序。/// </summary>/// <param name="args"></param>static void Main(string[] args){OrderByEx1();}class Pet{public string Name { get; set; }public int Age { get; set; }}public static void OrderByEx1(){Pet[] pets = { new Pet { Name="Barley", Age=8 },new Pet { Name="Boots", Age=4 },new Pet { Name="Whiskers", Age=1 } };// Sort the Pet objects in the array by Pet.Age.//按宠物年龄排序IEnumerable<Pet> query =pets.AsQueryable().OrderBy(pet => pet.Age);foreach (Pet pet in query)Console.WriteLine("{0} - {1}", pet.Name, pet.Age);}/*This code produces the following output:Whiskers - 1Boots - 4Barley - 8*/}
}

OtderByDescending用法:

namespace OrderByDescending
{class Program{/// <summary>/// OrderByDescending 降序/// Sorts the elements of a sequence in descending order./// 按降序对序列元素进行排序。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用*OrderByDescending<TSource,TKey>(IQueryable<TSource>, * Expression<Func<TSource,TKey>>, IComparer<TKey>)* 排序序列中的元素依次使用自定义比较器。*/OrderByDescendingEx1();}/// <summary>/// This IComparer class sorts by the fractional part of the decimal number./// </summary>public class SpecialComparer : IComparer<decimal>{/// <summary>/// Compare two decimal numbers by their fractional parts./// </summary>/// <param name="d1">The first decimal to compare.</param>/// <param name="d2">The second decimal to compare.</param>/// <returns>1 if the first decimal's fractional part /// is greater than the second decimal's fractional part,/// -1 if the first decimal's fractional/// part is less than the second decimal's fractional part,/// or the result of calling Decimal.Compare()/// if the fractional parts are equal.</returns>public int Compare(decimal d1, decimal d2){decimal fractional1, fractional2;// Get the fractional part of the first number.try{fractional1 = decimal.Remainder(d1, decimal.Floor(d1));}catch (DivideByZeroException){fractional1 = d1;}// Get the fractional part of the second number.try{fractional2 = decimal.Remainder(d2, decimal.Floor(d2));}catch (DivideByZeroException){fractional2 = d2;}if (fractional1 == fractional2)return Decimal.Compare(d1, d2);else if (fractional1 > fractional2)return 1;elsereturn -1;}}public static void OrderByDescendingEx1(){List<decimal> decimals =new List<decimal> { 6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m };// Sort the decimal values in descending order// by using a custom comparer.IEnumerable<decimal> query =decimals.AsQueryable().OrderByDescending(num => num, new SpecialComparer());foreach (decimal num in query)Console.WriteLine(num);}/*This code produces the following output:9.70.58.36.31.36.2*/}
}

Reverse用法:

namespace Reverse
{class Program{/// <summary>/// Reverse 反向/// Inverts the order of the elements in a sequence./// 反转序列中元素的排序/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用Reverse<TSource>(IQueryable<TSource>)颠倒数组中元素的顺序。*/char[] apple = { 'a', 'p', 'p', 'l', 'e' };// Reverse the order of the characters in the collection.//反转集合中字符的顺序IQueryable<char> reversed = apple.AsQueryable().Reverse();foreach (char chr in reversed)Console.Write(chr + " ");Console.WriteLine();/*This code produces the following output:e l p p a*/}}
}

Select用法:

namespace Select_01
{class Program{/// <summary>/// Select选择/// Projects each element of a sequence into a new form by incorporating the element's index./// 通过将元素的索引合并为一个序列的每个元素到一个新的表单中。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*The following code example demonstrates how to use * Select<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,TResult>>) * to project over a sequence of values and use the index of each element in the projected form.下面的代码示例演示如何使用Select<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,TResult>>) 项目的一个序列值和预计的形式使用每个元素的索引*/string[] fruits = { "apple", "banana", "mango", "orange","passionfruit", "grape" };// Project an anonymous type that contains the// index of the string in the source array, and// a string that contains the same number of characters// as the string's index in the source array.var query =fruits.AsQueryable().Select((fruit, index) =>new { index, str = fruit.Substring(0, index) });foreach (var obj in query)Console.WriteLine("{0}", obj);/*This code produces the following output:{ index = 0, str =  }{ index = 1, str = b }{ index = 2, str = ma }{ index = 3, str = ora }{ index = 4, str = pass }{ index = 5, str = grape }*/}}
}
namespace Select_02
{class Program{static void Main(string[] args){List<int> range =new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };// Project the square of each int value.//对每个int的值得平方进行投影IEnumerable<int> squares =range.AsQueryable().Select(x => x * x);foreach (int num in squares)Console.WriteLine(num);/*This code produces the following output:149162536496481100*/}}
}

SelectMany用法:

namespace SelectMany_01
{class Program{/// <summary>/// SelectMany 多项选择/// Projects each element of a sequence to an IEnumerable<T> /// and combines the resulting sequences into one sequence of type IQueryable<T>./// 项目的每一个元素的序列以IEnumerable <T>结合产生的序列类型IQueryable <T>序列。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用* SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>,* Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) * 进行一对多的投影在一个阵列。这个例子使用一个结果选择器函数来保存对应于最后调用的每个中间序列的源元素来选择。*/SelectManyEx3();}class PetOwner{public string Name { get; set; }public List<Pet> Pets { get; set; }}class Pet{public string Name { get; set; }public string Breed { get; set; }}public static void SelectManyEx3(){PetOwner[] petOwners ={ new PetOwner { Name="Higa",Pets = new List<Pet>{new Pet { Name="Scruffy", Breed="Poodle" },new Pet { Name="Sam", Breed="Hound" } } },new PetOwner { Name="Ashkenazi",Pets = new List<Pet>{new Pet { Name="Walker", Breed="Collie" },new Pet { Name="Sugar", Breed="Poodle" } } },new PetOwner { Name="Price",Pets = new List<Pet>{new Pet { Name="Scratches", Breed="Dachshund" },new Pet { Name="Diesel", Breed="Collie" } } },new PetOwner { Name="Hines",Pets = new List<Pet>{new Pet { Name="Dusty", Breed="Collie" } } }};// This query demonstrates how to obtain a sequence of// the names of all the pets whose breed is "Collie", while// keeping an association with the owner that owns the pet./*此查询演示如何获取序列所有宠物的品种是“牧羊犬”的名字,以及此宠物的拥有者。 */var query =petOwners.AsQueryable()// Create a sequence of ALL the Pet objects. Then// project an anonymous type that consists of each// Pet in the new sequence and the PetOwner object// from the initial array that corresponds to that pet./*创建所有宠物对象的序列。然后项目:每个类型的匿名类型宠物在新的序列和PetOwner对象从对应于该宠物的初始数组中。*/.SelectMany(owner => owner.Pets,(owner, pet) => new { owner, pet })// Filter the sequence of anonymous types to only// keep pets whose breed is "Collie"..Where(ownerAndPet => ownerAndPet.pet.Breed == "Collie")// Project an anonymous type that consists// of the pet owner's name and the pet's name..Select(ownerAndPet => new{Owner = ownerAndPet.owner.Name,Pet = ownerAndPet.pet.Name});// Print the results.打印结果foreach (var obj in query)Console.WriteLine(obj);}/* This code produces the following output:{ Owner = Ashkenazi, Pet = Walker }{ Owner = Price, Pet = Diesel }{ Owner = Hines, Pet = Dusty }*/}
}
namespace SelectMany_02
{class Program{static void Main(string[] args){SelectManyEx2();}class PetOwner{public string Name { get; set; }public List<string> Pets { get; set; }}public static void SelectManyEx2(){PetOwner[] petOwners ={ new PetOwner { Name="Higa, Sidney",Pets = new List<string>{ "Scruffy", "Sam" } },new PetOwner { Name="Ashkenazi, Ronen",Pets = new List<string>{ "Walker", "Sugar" } },new PetOwner { Name="Price, Vernette",Pets = new List<string>{ "Scratches", "Diesel" } },new PetOwner { Name="Hines, Patrick",Pets = new List<string>{ "Dusty" } } };// For each PetOwner element in the source array,// project a sequence of strings where each string// consists of the index of the PetOwner element in the// source array and the name of each pet in PetOwner.Pets.IEnumerable<string> query =petOwners.AsQueryable().SelectMany((petOwner, index) => petOwner.Pets.Select(pet => index + pet));foreach (string pet in query)Console.WriteLine(pet);}// This code produces the following output://// 0Scruffy// 0Sam// 1Walker// 1Sugar// 2Scratches// 2Diesel// 3Dusty}
}

SequenceEqual用法:

namespace SequenceEqual_01
{class Program{/// <summary>/// SequenceEqual 序列相同/// Determines whether two sequences are equal./// 确定两个序列是否相等/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用* SequenceEqual<TSource>(IQueryable<TSource>, IEnumerable<TSource>) * 两个序列是否相等。在这个例子中,序列是相等的。*/SequenceEqualEx1();}class Pet{public string Name { get; set; }public int Age { get; set; }}public static void SequenceEqualEx1(){Pet pet1 = new Pet { Name = "Turbo", Age = 2 };Pet pet2 = new Pet { Name = "Peanut", Age = 8 };// Create two lists of pets.//创建两个宠物列表List<Pet> pets1 = new List<Pet> { pet1, pet2 };List<Pet> pets2 = new List<Pet> { pet1, pet2 };// Determine if the lists are equal.//确定两个序列是否相等bool equal = pets1.AsQueryable().SequenceEqual(pets2);Console.WriteLine("The lists {0} equal.",equal ? "are" : "are not");}/*This code produces the following output:The lists are equal.*/}
}
namespace SequenceEqual_02
{class Program{static void Main(string[] args){/*下面的代码示例比较不相等的两个序列。*/SequenceEqualEx2();}class Pet{public string Name { get; set; }public int Age { get; set; }}public static void SequenceEqualEx2(){Pet pet1 = new Pet() { Name = "Turbo", Age = 2 };Pet pet2 = new Pet() { Name = "Peanut", Age = 8 };// Create two lists of pets.创建两个宠物列表System.Collections.Generic.List<Pet> pets1 = new List<Pet> { pet1, pet2 };List<Pet> pets2 = new List<Pet> {new Pet { Name = "Turbo", Age = 2 },new Pet { Name = "Peanut", Age = 8 }};// Determine if the lists are equal.确定两个序列是否相等bool equal = pets1.AsQueryable().SequenceEqual(pets2);Console.WriteLine("The lists {0} equal.", equal ? "are" : "are NOT");}/*This code produces the following output:The lists are NOT equal.*/}
}

Single用法:

namespace Single_01
{class Program{/// <summary>/// Single 单个/// Returns a single, specific element of a sequence./// 返回序列的单个、特定元素/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示如何使用 Single<TSource>(IQueryable<TSource>)选择一个数组的元素。*/// Create two arrays.创建两个序列string[] fruits1 = { "orange" };string[] fruits2 = { "orange", "apple" };// Get the only item in the first array.获取第一个数组中的惟一项。string fruit1 = fruits1.AsQueryable().Single();Console.WriteLine("First query: " + fruit1);try{// Try to get the only item in the second array.尝试获取第二个数组中的惟一项。string fruit2 = fruits2.AsQueryable().Single();Console.WriteLine("Second query: " + fruit2);}catch (InvalidOperationException){Console.WriteLine("Second query: The collection does not contain exactly one element."//集合不完全包含一个元素。);}/*This code produces the following output:First query: orangeSecond query: The collection does not contain exactly one element*/}}
}
namespace Single_02
{class Program{static void Main(string[] args){/*The following code example demonstrates how to use * Single<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)* to select the only element of an array that satisfies a condition.*下面的代码示例演示如何使用* Single<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)* 选择一个满足条件的元素的数组。*/string[] fruits = { "apple", "banana", "mango","orange", "passionfruit", "grape" };// Get the only string in the array whose length is greater than 10.//获取长度大于10的数组中的唯一字符串。string fruit1 = fruits.AsQueryable().Single(fruit => fruit.Length > 10);Console.WriteLine("First Query: " + fruit1);try{// Try to get the only string in the array// whose length is greater than 15.//尝试获取数组中的唯一字符串。//其长度大于15。string fruit2 = fruits.AsQueryable().Single(fruit => fruit.Length > 15);Console.WriteLine("Second Query: " + fruit2);}catch (System.InvalidOperationException){Console.Write("Second Query: The collection does not contain ");//集合不包含Console.WriteLine("exactly one element whose length is greater than 15.");}/*This code produces the following output:First Query: passionfruitSecond Query: The collection does not contain exactly one element whose length is greater than 15.*/}}
}

SingleOrDefault用法:

namespace SingleOrDefault_01
{class Program{/// <summary>/// SingleOrDefault 单一或默认/// Returns a single, specific element of a sequence, or a default value if no such element is found./// 返回序列的一个单独的特定元素,如果没有找到这样的元素,则返回一个默认值。/// </summary>/// <param name="args"></param>static void Main(string[] args){// Create two arrays. The second is empty.创建两个数组,第二个数组为空string[] fruits1 = { "orange" };string[] fruits2 = { };// Get the only item in the first array, or else// the default value for type string (null).string fruit1 = fruits1.AsQueryable().SingleOrDefault();Console.WriteLine("First Query: " + fruit1);// Get the only item in the second array, or else// the default value for type string (null). string fruit2 = fruits2.AsQueryable().SingleOrDefault();Console.WriteLine("Second Query: " +(String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2));/*This code produces the following output:First Query: orangeSecond Query: No such string!*/int[] pageNumbers = { };// Setting the default value to 1 after the query.int pageNumber1 = pageNumbers.AsQueryable().SingleOrDefault();if (pageNumber1 == 0){pageNumber1 = 1;}Console.WriteLine("The value of the pageNumber1 variable is {0}", pageNumber1);// Setting the default value to 1 by using DefaultIfEmpty() in the query.int pageNumber2 = pageNumbers.AsQueryable().DefaultIfEmpty(1).Single();Console.WriteLine("The value of the pageNumber2 variable is {0}", pageNumber2);/*This code produces the following output:The value of the pageNumber1 variable is 1The value of the pageNumber2 variable is 1*/}}
}

Skip用法:

namespace Skip
{class Program{/// <summary>/// Skip 跳过/// 在序列中绕过指定数量的元素,然后返回剩余的元素。/// </summary>/// <param name="args"></param>static void Main(string[] args){int[] grades = { 59, 82, 70, 56, 92, 98, 85 };// Sort the grades in descending order and// get all except the first three.IEnumerable<int> lowerGrades =grades.AsQueryable().OrderByDescending(g => g).Skip(3);Console.WriteLine("All grades except the top three are:");foreach (int grade in lowerGrades)Console.WriteLine(grade);/*This code produces the following output:All grades except the top three are:82705956*/}}
}

SkipLast用法:

namespace SkipLast
{class Program{static void Main(string[] args){int[] grades = {2, 92, 98, 85 };IEnumerable<int> lowerGrades =grades.AsQueryable().Select(g => g).SkipLast(3);Console.WriteLine("All grades except the top three are:");foreach (int grade in lowerGrades)Console.WriteLine(grade);/*This code produces the following output:          59827056*/}}
}

SkipWhile用法:

namespace SkipWhile
{class Program{/// <summary>/// SkipWhile/// 只要指定条件为真,则在序列中绕过元素,然后返回其余元素。/// </summary>/// <param name="args"></param>static void Main(string[] args){int[] grades = { 59, 82, 70, 56, 92, 98, 85 };// Get all grades less than 80 by first// sorting the grades in descending order and then// taking all the grades after the first grade// that is less than 80./*SkipWhile需要注意的地方:筛选结果要注意“>,<,=”符号的变化与“OrderByDescending,OrderBy等有关,否则会导致筛选结果的不正确*/IEnumerable<int> lowerGrades =grades.AsQueryable().OrderByDescending(grade => grade).SkipWhile(grade => grade >= 80);Console.WriteLine("All grades below 80:");foreach (int grade in lowerGrades)Console.WriteLine(grade);/*This code produces the following output:All grades below 80:705956*/int[] amounts = { 5000, 2500, 9000, 8000,6500, 4000, 1500, 5500 };// Skip over amounts in the array until the first amount// that is less than or equal to the product of its// index in the array and 1000. Take the remaining items.IEnumerable<int> query =amounts.AsQueryable().SkipWhile((amount, index) => amount > index * 1000);foreach (int amount in query)Console.WriteLine(amount);/*This code produces the following output:400015005500*/}}
}

Sum用法:

namespace Sum
{class Program{/// <summary>/// Sum 和/// 计算一个数值序列的和/// </summary>/// <param name="args"></param>static void Main(string[] args){/*The following code example demonstrates how to use Sum(IQueryable<Single>) to sum the values of a sequence.下面的代码示例演示如何使用Sum(IQueryable<Single>)求和一个序列的值。*/List<float> numbers = new List<float> { 43.68F, 1.25F, 583.7F, 6.5F };float sum = numbers.AsQueryable().Sum();//float sum = numbers.Sum();Console.WriteLine("The sum of the numbers is {0}.", sum);/*This code produces the following output:The sum of the numbers is 635.13.*//*The following code example demonstrates how to use Sum(IQueryable<Nullable<Single>>) to sum the values of a sequence.下面的代码示例演示如何使用Sum(IQueryable<Nullable<Single>>) 求和一个序列的值。*///注意“float?[]”与“float?”中的“?”,第一个问号(float?[])表示数组中可以有空值,第二个问号(float?)表示要与“float?[]”类型一致float?[] points = { null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F };float? sum1 = points.AsQueryable().Sum();//float? sum1 = points.Sum();Console.WriteLine("Total points earned: {0}", sum1);/*This code produces the following output:Total points earned: 311.39*/}}
}
    
namespace Sum_02
{class Program{static void Main(string[] args){SumEx1();}class Package{public string Company { get; set; }public double Weight { get; set; }}public static void SumEx1(){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 } };double totalWeight = packages.Sum(x => x.Weight);Console.WriteLine("The total weight of the packages is: {0}", totalWeight);}/*This code produces the following output:The total weight of the packages is: 83.7*/}
}

Take用法:

namespace Take
{class Program{/// <summary>/// Take 拿,取出/// 从序列的开始返回指定数目的连续元素。/// </summary>/// <param name="args"></param>static void Main(string[] args){int[] grades = { 59, 82, 70, 56, 92, 98, 85 };IEnumerable<int> topThreeGrades =grades.OrderByDescending(grade => grade).Take(3);//降序后结果集:98 92 85 82 70 59 56  Take(3)取前面三个Console.WriteLine("The top three grades are:");foreach (int grade in topThreeGrades){Console.WriteLine(grade);}/*This code produces the following output:The top three grades are:989285*/}}
}

TakeLast用法:

namespace TakeLast
{class Program{static void Main(string[] args){int[] grades = { 59, 82, 70, 56, 92, 98, 85 };IEnumerable<int> topThreeGrades =grades.OrderByDescending(grade => grade).TakeLast(3);//降序后结果集:98 92 85 82 70 59 56  TakeLast(3)取最后面面三个70 59 56Console.WriteLine("The top three grades are:");foreach (int grade in topThreeGrades){Console.WriteLine(grade);}/*This code produces the following output:The top three grades are:929885*/}}
}

TakeWhilel用法:

namespace TakeWhile
{class Program{/// <summary>/// TakeWhile /// Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements./// 只要指定的条件为true,则从序列中返回元素,然后跳过其余元素。/// </summary>/// <param name="args"></param>static void Main(string[] args){string[] fruits = { "apple", "passionfruit", "banana", "mango","orange", "blueberry", "grape", "strawberry" };// Take strings from the array until a string whose length// is less than its index in the array is found./*从数组中获取字符串直到长度小于数组中的索引*/IEnumerable<string> query =fruits.AsQueryable().TakeWhile((fruit, index) => fruit.Length >= index);foreach (string fruit in query)Console.WriteLine(fruit);/*This code produces the following output:applepassionfruitbananamangoorangeblueberry*/}}
}

ThenBy用法:

namespace ThenBy
{class Program{/// <summary>/// ThenBy 然后通过/// 按升序对序列中的元素执行后续排序。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*The following code example demonstrates how to use* ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>) * to perform a secondary ordering of the elements in a sequence.下面的代码示例演示如何使用ThenBy<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>) 执行一个序列中元素的二次排序。*/string[] fruits = { "grape", "passionfruit", "banana", "apple","orange", "raspberry", "mango", "blueberry" };// Sort the strings first by their length and then // alphabetically by passing the identity selector function./*首先按字符串的长度排序,然后按字母顺序传递身份选择器函数。*/IEnumerable<string> query =fruits.AsQueryable().OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);foreach (string fruit in query)Console.WriteLine(fruit);/*This code produces the following output:applegrapemangobananaorangeblueberryraspberrypassionfruit*/}}
}

ThenByDescending用法:

namespace ThenByDescending
{class Program{/// <summary>/// ThenByDescending 二次排序降序/// 按键顺序按顺序降序执行元素顺序。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*The following code example demonstrates how to use * ThenByDescending<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) * to perform a secondary ordering of the elements in a sequence in descending order by using a custom comparer.下面的代码示例演示如何使用ThenByDescending<TSource,TKey>(IOrderedQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TKey>) 执行一个序列中元素的二次排序依次使用自定义比较器。*/ThenByDescendingEx1();}public class CaseInsensitiveComparer : IComparer<string>{public int Compare(string x, string y){return string.Compare(x, y, true);}}public static void ThenByDescendingEx1(){string[] fruits ={ "apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE" };// Sort the strings first ascending by their length and // then descending using a custom case insensitive comparer./*首先按字符串长度和升序排序字符串。然后下行使用自定义的不区分大小写的比较。*/IEnumerable<string> query =fruits.AsQueryable().OrderBy(fruit => fruit.Length).ThenByDescending(fruit => fruit, new CaseInsensitiveComparer());foreach (string fruit in query)Console.WriteLine(fruit);}/*This code produces the following output:apPLeappleAPpleapPLEorangeORANGEbaNanABAnana*/}
}

Union用法:

namespace Union并集
{class Program{/// <summary>/// Union 并集/// 产生两个序列的集合并集。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*The following code example demonstrates how to use* Union<TSource>(IQueryable<TSource>, IEnumerable<TSource>)* to obtain the set union of two sequences.*下面的代码示例演示如何使用*Union<TSource>(IQueryable<TSource>, IEnumerable<TSource>)*两个序列的并集。*/int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };// Get the set union of the items in the two arrays.//获取两个数组中项的集合联合。    并集IEnumerable<int> union = ints1.AsQueryable().Union(ints2);foreach (int num in union)Console.Write("{0} ", num);/*This code produces the following output:5 3 9 7 8 6 4 1 0*/}}
}

Where用法:

namespace Where_01
{class Program{/// <summary>/// Where/// Filters a sequence of values based on a predicate.///根据判断(条件)过滤一系列值。/// </summary>/// <param name="args"></param>static void Main(string[] args){int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 };// Get all the numbers that are less than or equal to// the product of their index in the array and 10.IEnumerable<int> query =numbers.AsQueryable().Where((number, index) => number <= index * 10);foreach (int number in query)Console.WriteLine(number);/*This code produces the following output:0201540*/}}
}

namespace Where_02
{class Program{static void Main(string[] args){/*下面的代码示例演示如何使用Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)过滤序列。*/List<string> fruits =new List<string> { "apple", "passionfruit", "banana", "mango","orange", "blueberry", "grape", "strawberry" };// Get all strings whose length is less than 6.//获取长度小于6的所有字符串。IEnumerable<string> query =fruits.AsQueryable().Where(fruit => fruit.Length < 6);foreach (string fruit in query)Console.WriteLine(fruit);/*This code produces the following output:applemangogrape*/}}
}

Zip用法:

namespace Zip
{class Program{/// <summary>/// Zip /// 使用指定的判断函数合并两个序列。/// </summary>/// <param name="args"></param>static void Main(string[] args){/*下面的代码示例演示了如何使用Zip方法合并两个序列。*/int[] numbers = { 1, 2, 3, 4 };string[] words = { "one", "two", "three" };var numbersAndWords = numbers.AsQueryable().Zip(words, (first, second) => first + " " + second);foreach (var item in numbersAndWords)Console.WriteLine(item);// This code produces the following output:// 1 one// 2 two// 3 three}}
}
namespace 分页
{class Program{     static void Main(string[] args){//Math.Ceiling(Convert.ToDouble(grades.Length) / 2);//Math.Ceiling()向上取整var PegeTotal =3;//每页多少条数据float[] grades = { 59, 82, 70, 56, 92, 98, 85,11,22,33 };for (var i = 0; i < Math.Ceiling(grades.Length/ (double)PegeTotal); i++){Console.WriteLine($"第{i + 1}页");foreach (var grade in grades.Skip(i * PegeTotal).Take(PegeTotal)){Console.WriteLine(grade);}}}}
}

          如能看完以上的所有用例,对于使用Linq处理数据基本上是得心应手了!

          如果以上用例有什么写得不好或者有写错了的地方,欢迎指出,本人定会虚心受教!

          欢迎转载文章,转载需标明出处!

















































更多推荐

C#之Linq入门首选案例

本文发布于:2024-02-28 06:19:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1768616.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:入门   首选   案例   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!