// Determine whether any string in the array is longer than "banana". string longestName = fruits.Aggregate("banana", (longest, next) => next.Length > longest.Length ? next : longest, // Return the final result as an upper case string. fruit => fruit.ToUpper());
Console.WriteLine( "The fruit with the longest name is {0}.", longestName);
// This code produces the following output: // // The fruit with the longest name is PASSIONFRUIT.
1 2 3 4 5 6 7 8 9 10 11
int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };
// Count the even numbers in the array, using a seed value of 0. int numEven = ints.Aggregate(0, (total, next) => next % 2 == 0 ? total + 1 : total);
Console.WriteLine("The number of even integers is: {0}", numEven);
// This code produces the following output: // // The number of even integers is: 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
string sentence = "the quick brown fox jumps over the lazy dog";
// Split the string into individual words. string[] words = sentence.Split(' ');
// Prepend each word to the beginning of the // new sentence to reverse the word order. string reversed = words.Aggregate((workingSentence, next) => next + " " + workingSentence);
Console.WriteLine(reversed);
// This code produces the following output: // // dog lazy the over jumps fox brown quick the
classPet { publicstring Name { get; set; } publicint Age { get; set; } }
publicstaticvoidAllEx() { // Create an array of Pets. Pet[] pets = { new Pet { Name="Barley", Age=10 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=6 } };
// Determine whether all pet names // in the array start with 'B'. bool allStartWithB = pets.All(pet => pet.Name.StartsWith("B"));
Console.WriteLine( "{0} pet names start with 'B'.", allStartWithB ? "All" : "Not all"); }
// This code produces the following output: // // Not all pet names start with 'B'.
publicstaticvoidAllEx2() { 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. IEnumerable<string> names = from person in people where 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 */ }
publicstaticvoidAnyEx2() { 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 Person { LastName = "Philips", Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, new Pet { Name = "Rover", Age = 13}} } };
// Determine which people have a non-empty Pet array. IEnumerable<string> names = from person in people where person.Pets.Any() select person.LastName;
foreach (string name in names) { Console.WriteLine(name); }
/* This code produces the following output: Haas Fakhouri Philips */ }
publicstaticvoidAnyEx3() { // Create an array of Pets. Pet[] pets = { new Pet { Name="Barley", Age=8, Vaccinated=true }, new Pet { Name="Boots", Age=4, Vaccinated=false }, new Pet { Name="Whiskers", Age=1, Vaccinated=false } };
// Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = pets.Any(p => p.Age > 1 && p.Vaccinated == false);
Console.WriteLine( "There {0} unvaccinated animals over age one.", unvaccinated ? "are" : "are not any"); }
// This code produces the following output: // // There are unvaccinated animals over age one.
// Custom class. classClump<T> : List<T> { // Custom implementation of Where(). public IEnumerable<T> Where(Func<T, bool> predicate) { Console.WriteLine("In Clump's implementation of Where()."); return Enumerable.Where(this, predicate); } }
staticvoidAsEnumerableEx1() { // Create a new Clump<T> object. Clump<string> fruitClump = new Clump<string> { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" };
// First call to Where(): // Call Clump's Where() method with a predicate. IEnumerable<string> query1 = fruitClump.Where(fruit => fruit.Contains("o"));
Console.WriteLine("query1 has been created.\n");
// Second call to Where(): // First call AsEnumerable() to hide Clump's Where() method and thereby // force System.Linq.Enumerable's Where() method to be called. IEnumerable<string> query2 = fruitClump.AsEnumerable().Where(fruit => fruit.Contains("o"));
// Display the output. Console.WriteLine("query2 has been created."); }
// This code produces the following output: // // In Clump's implementation of Where(). // query1 has been created. // // query2 has been created.
classPet { publicstring Name { get; set; } publicint 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; }
try { int numberOfFruits = fruits.Count(); Console.WriteLine( "There are {0} fruits in the collection.", numberOfFruits); } catch (OverflowException) { Console.WriteLine("The count is too large to store as an Int32."); Console.WriteLine("Try using the LongCount() method instead."); }
// This code produces the following output: // // There are 6 fruits in the collection.
publicstaticvoidCountEx2() { Pet[] pets = { new Pet { Name="Barley", Vaccinated=true }, new Pet { Name="Boots", Vaccinated=false }, new Pet { Name="Whiskers", Vaccinated=false } };
try { int numberUnvaccinated = pets.Count(p => p.Vaccinated == false); Console.WriteLine("There are {0} unvaccinated animals.", numberUnvaccinated); } catch (OverflowException) { Console.WriteLine("The count is too large to store as an Int32."); Console.WriteLine("Try using the LongCount() method instead."); } }
// This code produces the following output: // // There are 2 unvaccinated animals.
classPet { publicstring Name { get; set; } publicint Age { get; set; } }
publicstaticvoidDefaultIfEmptyEx1() { 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: Barley Boots Whiskers */
1 2 3 4 5 6 7 8 9 10 11 12
List<int> numbers = new List<int>();
foreach (int number in numbers.DefaultIfEmpty()) { Console.WriteLine(number); }
List<string[]> namesList = new List<string[]> { names1, names2, names3 };
// Only include arrays that have four or more elements IEnumerable<string> allNames = namesList.Aggregate(Enumerable.Empty<string>(), (current, next) => next.Length > 3 ? current.Union(next) : current);
foreach (string name in allNames) { Console.WriteLine(name); }
/* This code produces the following output: Adams, Terry Andersen, Henriette Thaulow Hedlund, Magnus Ito, Shu Solanki, Ajay Hoeing, Helge Potra, Cristina Iallo, Lucio */
// Custom comparer for the Product class classProductComparer : IEqualityComparer<Product> { // Products are equal if their names and product numbers are equal. publicboolEquals(Product x, Product y) {
//Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) returntrue;
//Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) returnfalse;
//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.
publicintGetHashCode(Product product) { //Check whether the object is null if (Object.ReferenceEquals(product, null)) return0;
//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; } }
Product[] fruits1 = { new Product { Name = "apple", Code = 9 }, new Product { Name = "orange", Code = 4 }, new Product { Name = "lemon", Code = 12 } };
Product[] fruits2 = { new Product { Name = "apple", Code = 9 } };
// Get all the elements from the first array // except for the elements from the second array.
IEnumerable<Product> except = fruits1.Except(fruits2, new ProductComparer());
// Setting the default value to 1 after the query. int firstMonth1 = months.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. int firstMonth2 = months.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 1 The value of the firstMonth2 variable is 1 */
classPet { publicstring Name { get; set; } publicdouble Age { get; set; } }
publicstaticvoidGroupByEx4() { // 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.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: 8 Number of pets in this age group: 1 Minimum age: 8.3 Maximum age: 8.3 Age group: 4 Number of pets in this age group: 2 Minimum age: 4.3 Maximum age: 4.9 Age group: 1 Number of pets in this age group: 1 Minimum age: 1.5 Maximum age: 1.5 */ }
classPet { publicstring Name { get; set; } publicint Age { get; set; } }
// Uses method-based query syntax. publicstaticvoidGroupByEx1() { // Create a list of pets. 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 Age as the key value // and selecting only the pet's Name for each value. IEnumerable<IGrouping<int, string>> query = pets.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: 8 Barley 4 Boots Daisy 1 Whiskers */
classPet { publicstring Name { get; set; } publicdouble Age { get; set; } }
publicstaticvoidGroupByEx3() { // 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.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: 8 Number of pets in this age group: 1 Minimum age: 8.3 Maximum age: 8.3 Age group: 4 Number of pets in this age group: 2 Minimum age: 4.3 Maximum age: 4.9 Age group: 1 Number of pets in this age group: 1 Minimum age: 1.5 Maximum age: 1.5 */ }
classPet { publicstring Name { get; set; } public Person Owner { get; set; } }
publicstaticvoidGroupJoinEx1() { 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 they own. var query = people.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: Daisy Adams, Terry: Barley Boots Weiss, Charlotte: Whiskers */
// Custom comparer for the Product class classProductComparer : IEqualityComparer<Product> { // Products are equal if their names and product numbers are equal. publicboolEquals(Product x, Product y) {
//Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) returntrue;
//Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) returnfalse;
//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.
publicintGetHashCode(Product product) { //Check whether the object is null if (Object.ReferenceEquals(product, null)) return0;
//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; } }
Product[] store1 = { new Product { Name = "apple", Code = 9 }, new Product { Name = "orange", Code = 4 } };
Product[] store2 = { new Product { Name = "apple", Code = 9 }, new Product { Name = "lemon", Code = 12 } };
// Get the products from the first array // that have duplicates in the second array.
IEnumerable<Product> duplicates = store1.Intersect(store2, new ProductComparer());
classPet { publicstring Name { get; set; } public Person Owner { get; set; } }
publicstaticvoidJoinEx1() { 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 of Person-Pet pairs where // each element is an anonymous type that contains a // Pet's name and the name of the Person that owns the Pet. var query = people.Join(pets, person => person, pet => pet.Owner, (person, pet) => new { OwnerName = person.Name, Pet = pet.Name });
// Setting the default value to 1 after the query. int lastDay1 = daysOfMonth.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. int lastDay2 = daysOfMonth.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 1 The value of the lastDay2 variable is 1 */
classPet { publicstring Name { get; set; } publicint Age { get; set; } }
publicstaticvoidLongCountEx2() { Pet[] pets = { new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 } };
constint Age = 3;
long count = pets.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. */
///<summary> /// This class implements IComparable to be able to /// compare one Pet to another Pet. ///</summary> classPet : IComparable<Pet> { publicstring Name { get; set; } publicint Age { get; set; }
///<summary> /// Compares this Pet to another Pet by /// summing each Pet's age and name length. ///</summary> ///<param name="other">The Pet to compare this Pet to.</param> ///<returns>-1 if this Pet is 'less' than the other Pet, /// 0 if they are equal, /// or 1 if this Pet is 'greater' than the other Pet.</returns> int IComparable<Pet>.CompareTo(Pet other) { int sumOther = other.Age + other.Name.Length; int sumThis = this.Age + this.Name.Length;
///<summary> /// This class implements IComparable in order to /// be able to compare different Pet objects. ///</summary> classPet : IComparable<Pet> { publicstring Name { get; set; } publicint Age { get; set; }
///<summary> /// Compares this Pet's age to another Pet's age. ///</summary> ///<param name="other">The Pet to compare this Pet to.</param> ///<returns>-1 if this Pet's age is smaller, /// 0 if the Pets' ages are equal, or /// 1 if this Pet's age is greater.</returns> int IComparable<Pet>.CompareTo(Pet other) { if (other.Age > this.Age) return-1; elseif (other.Age == this.Age) return0; else return1; } }
publicstaticvoidMinEx3() { Pet[] pets = { new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 } };
Pet min = pets.Min();
Console.WriteLine( "The 'minimum' animal is {0}.", min.Name); }
/* This code produces the following output: The 'minimum' animal is Whiskers. */
// Apply OfType() to the ArrayList. IEnumerable<string> query1 = fruits.OfType<string>();
Console.WriteLine("Elements of type 'string' are:"); foreach (string fruit in query1) { Console.WriteLine(fruit); }
// The following query shows that the standard query operators such as // Where() can be applied to the ArrayList type after calling OfType(). IEnumerable<string> query2 = fruits.OfType<string>().Where(fruit => fruit.Contains('n', StringComparison.CurrentCultureIgnoreCase));
Console.WriteLine("\nThe following strings contain 'n':"); foreach (string fruit in query2) { Console.WriteLine(fruit); }
// This code produces the following output: // // Elements of type 'string' are: // Mango // Orange // Apple // Banana // // The following strings contain 'n': // Mango // Orange // Banana
///<summary> /// This IComparer class sorts by the fractional part of the decimal number. ///</summary> publicclassSpecialComparer : 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> publicintCompare(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; }
// Generate a sequence of integers from 1 to 10 // and then select their squares. IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
foreach (int num in squares) { Console.WriteLine(num); }
/* This code produces the following output: 1 4 9 16 25 36 49 64 81 100 */
IEnumerable<string> strings = Enumerable.Repeat("I like programming.", 15);
foreach (String str in strings) { Console.WriteLine(str); }
/* This code produces the following output: I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. I like programming. */
var query = fruits.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 } */
classPetOwner { publicstring Name { get; set; } public List<string> Pets { get; set; } }
publicstaticvoidSelectManyEx3() { PetOwner[] petOwners = { new PetOwner { Name="Higa", Pets = new List<string>{ "Scruffy", "Sam" } }, new PetOwner { Name="Ashkenazi", Pets = new List<string>{ "Walker", "Sugar" } }, new PetOwner { Name="Price", Pets = new List<string>{ "Scratches", "Diesel" } }, new PetOwner { Name="Hines", Pets = new List<string>{ "Dusty" } } };
// Project the pet owner's name and the pet's name. var query = petOwners .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName }) .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S")) .Select(ownerAndPet => new { Owner = ownerAndPet.petOwner.Name, Pet = ownerAndPet.petName } );
// Print the results. foreach (var obj in query) { Console.WriteLine(obj); } }
// This code produces the following output: // // {Owner=Higa, Pet=Scruffy} // {Owner=Higa, Pet=Sam} // {Owner=Ashkenazi, Pet=Sugar} // {Owner=Price, Pet=Scratches}
classPetOwner { publicstring Name { get; set; } public List<String> Pets { get; set; } }
publicstaticvoidSelectManyEx1() { 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" } } };
// Query using SelectMany(). IEnumerable<string> query1 = petOwners.SelectMany(petOwner => petOwner.Pets);
Console.WriteLine("Using SelectMany():");
// Only one foreach loop is required to iterate // through the results since it is a // one-dimensional collection. foreach (string pet in query1) { Console.WriteLine(pet); }
// This code shows how to use Select() // instead of SelectMany(). IEnumerable<List<String>> query2 = petOwners.Select(petOwner => petOwner.Pets);
Console.WriteLine("\nUsing Select():");
// Notice that two foreach loops are required to // iterate through the results // because the query returns a collection of arrays. foreach (List<String> petList in query2) { foreach (string pet in petList) { Console.WriteLine(pet); } Console.WriteLine(); } }
/* This code produces the following output: Using SelectMany(): Scruffy Sam Walker Sugar Scratches Diesel Using Select(): Scruffy Sam Walker Sugar Scratches Diesel */
classPetOwner { publicstring Name { get; set; } public List<string> Pets { get; set; } }
publicstaticvoidSelectManyEx2() { 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" } } };
// Project the items in the array by appending the index // of each PetOwner to each pet's name in that petOwner's // array of pets. IEnumerable<string> query = petOwners.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
classPet { publicstring Name { get; set; } publicint Age { get; set; } }
publicstaticvoidSequenceEqualEx2() { 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> { new Pet { Name = "Turbo", Age = 2 }, new Pet { Name = "Peanut", Age = 8 } };
// Custom comparer for the Product class classProductComparer : IEqualityComparer<Product> { // Products are equal if their names and product numbers are equal. publicboolEquals(Product x, Product y) {
//Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) returntrue;
//Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) returnfalse;
//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.
publicintGetHashCode(Product product) { //Check whether the object is null if (Object.ReferenceEquals(product, null)) return0;
//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; } }
Product[] storeA = { new Product { Name = "apple", Code = 9 }, new Product { Name = "orange", Code = 4 } };
Product[] storeB = { new Product { Name = "apple", Code = 9 }, new Product { Name = "orange", Code = 4 } };
bool equalAB = storeA.SequenceEqual(storeB, new ProductComparer());
Console.WriteLine("Equal? " + equalAB);
/* This code produces the following output: Equal? True */
/* This code produces the following output: passionfruit */
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
string fruit2 = null;
try { fruit2 = fruits.Single(fruit => fruit.Length > 15); } catch (System.InvalidOperationException) { Console.WriteLine(@"The collection does not contain exactly one element whose length is greater than 15."); }
Console.WriteLine(fruit2);
// This code produces the following output: // // The collection does not contain exactly // one element whose length is greater than 15.
1 2 3 4 5 6 7 8 9 10 11
string[] fruits1 = { "orange" };
string fruit1 = fruits1.Single();
Console.WriteLine(fruit1);
/* This code produces the following output: orange */
// Setting the default value to 1 after the query. int pageNumber1 = pageNumbers.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.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 1 The value of the pageNumber2 variable is 1 */
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: 98 92 85 */
// Sort the strings first by their length and then //alphabetically by passing the identity selector function. IEnumerable<string> query = fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);
foreach (string fruit in query) { Console.WriteLine(fruit); }
/* This code produces the following output: apple grape mango banana orange blueberry raspberry passionfruit */
// Sort the strings first ascending by their length and // then descending using a custom case insensitive comparer. IEnumerable<string> query = fruits .OrderBy(fruit => fruit.Length) .ThenByDescending(fruit => fruit, new CaseInsensitiveComparer());
foreach (string fruit in query) { Console.WriteLine(fruit); } }
/* This code produces the following output: apPLe apple APple apPLE orange ORANGE baNanA BAnana */
publicstaticvoidToDictionaryEx1() { 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 } };
// Create a Dictionary of Package objects, // using TrackingNumber as the key. Dictionary<long, Package> dictionary = packages.ToDictionary(p => p.TrackingNumber);
publicstaticvoidToLookupEx1() { // Create a list of Packages. 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 = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L }, new Package { Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L } };
// Create a Lookup to organize the packages. // Use the first character of Company as the key value. // Select Company appended to TrackingNumber // as the element values of the Lookup. ILookup<char, string> lookup = packages .ToLookup(p => p.Company[0], p => p.Company + " " + p.TrackingNumber);
// Iterate through each IGrouping in the Lookup. foreach (IGrouping<char, string> packageGroup in lookup) { // Print the key value of the IGrouping. Console.WriteLine(packageGroup.Key); // Iterate through each value in the // IGrouping and print its value. foreach (string str in packageGroup) Console.WriteLine(" {0}", str); } }
/* This code produces the following output: C Coho Vineyard 89453312 Contoso Pharmaceuticals 670053128 L Lucerne Publishing 89112755 W Wingtip Toys 299456122 Wide World Importers 4665518773 */
// Custom comparer for the Product class classProductComparer : IEqualityComparer<Product> { // Products are equal if their names and product numbers are equal. publicboolEquals(Product x, Product y) {
//Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) returntrue;
//Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) returnfalse;
//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.
publicintGetHashCode(Product product) { //Check whether the object is null if (Object.ReferenceEquals(product, null)) return0;
//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; } }
Product[] store10 = { new Product { Name = "apple", Code = 9 }, new Product { Name = "orange", Code = 4 } };
Product[] store20 = { new Product { Name = "apple", Code = 9 }, new Product { Name = "lemon", Code = 12 } };
//Get the products from the both arrays //excluding duplicates.
IEnumerable<Product> union = store10.Union(store20, new ProductComparer());