using System;
using System.Collections.Generic;
using System.Linq;
//for the Enumerable Methods
namespace LinQ
{
internal class Program
{
private static void Main(string[] args)
{
//******************************************************************************int Distinct
//DistinctTest();
//******************************************************************************class Distinct
//DistinctClassTest();
******************************************************************************Aggregate
//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);
******************************************************************************Aggregate
//string[] fruits = { "apple", "mango", "orange", "passionfruit", "bananaTest333","grape" };
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.
// ABC => ABC.ToUpper());
//Console.WriteLine(
// "The fruit with the longest name is {0}.",
// longestName);
******************************************************************************
For Array All or Find All function
AllEx();
****************************************************************************** List Any
//List<int> numbers = new List<int> { 1, 2 };
//bool hasElements = numbers.Any();
//Console.WriteLine("The list {0} empty.",
// hasElements ? "is not" : "is");
//****************************************************************************** List Any
//AnyEx2();
//****************************************************************************** AsEnumerableEx1
//AsEnumerableEx1();
//****************************************************************************** IEnumerable
//AsEnumerableExtest();
//****************************************************************************** Average double
//List<int> grades = new List<int> { 78, 92, 100, 37, 81 };
//double average = grades.Average();
//Console.WriteLine("The average grade is {0}.", average);
//****************************************************************************** Average longs
//long?[] longs = { null, 10007L, 37L, 399846234235L };
****************************************************************************** Average decimal
//long?[] longs = { null, 1L, 2L, 3 };
//double? average = longs.Average();
//decimal?[] dec = { null, 1m, 2m, 4m };
//decimal? averageDec = dec.Average();
//Console.WriteLine("The average is {0}.", average);
//Console.WriteLine("The average is {0}.", averageDec);
//****************************************************************************** Average decimal
//string[] numbers = { "10007", "37", "299846234235" };
//double average = numbers.Average(num => Convert.ToInt64(num));
//Console.WriteLine("The average is {0}.", average);
//****************************************************************************** Average double
//string[] numbers = { "10007", "37", "299846234235" };
//double average = numbers.Average(num => Convert.ToInt64(num));
//decimal dec = numbers.Average(num => Convert.ToDecimal(num));
//Console.WriteLine("The average is {0}.", average);
//Console.WriteLine("The average is {0}.", dec);
//****************************************************************************** Average double
//string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" };
//double average = fruits.Average(s => s.Length);
//Console.WriteLine("The average string length is {0}.", average);
//****************************************************************************** Average int
//string[] numbers = { "10007", "37", "299846234235" };
//double average = numbers.Average(num => Convert.ToInt64(num));
//Console.WriteLine("The average is {0}.", average);
//****************************************************************************** Max long
//List<long> longs = new List<long> { 4294967296L, 466855135L, 81125L };
//long max = longs.Max();
//Console.WriteLine("The largest number is {0}.", max);
//****************************************************************************** Min long
//List<long> longs = new List<long> { 4294967296L, 466855135L, 81125L };
//long max = longs.Min();
//Console.WriteLine("The largest number is {0}.", max);
//****************************************************************************** Max long
//MaxEx3();
//MaxEx4();
//****************************************************************************** Sum
//SumEx1();
//****************************************************************************** Take
//int[] grades = { 59, 82, 70, 56, 92, 98, 85 };
//IEnumerable<int> topThreeGrades =
// grades.OrderByDescending(grade => grade).Take(3);
//Console.WriteLine("The top three grades are:");
//foreach (int grade in topThreeGrades)
//{
// Console.WriteLine(grade);
//}
****************************************************************************** Take
//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 } };
//IEnumerable<Package> topPackage = packages.OrderByDescending(package => package.Weight).Take(2);
//foreach (var package in topPackage)
//{
// Console.WriteLine(package.Company);
//}
//****************************************************************************** Select
//
//IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * (x + 1));
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
//foreach (int num in squares)
//{
// Console.WriteLine(num);
//}
//string[] fruits = { "apple", "banana", "mango", "orange",
// "passionfruit", "grape" };
//var query = fruits.Select((fruit, index) => new { index, str = fruit.Substring(0, index) });
//foreach (var obj in query)
//{
// Console.WriteLine("{0}", obj);
//}
****************************************************************************** Demo Cast
//System.Collections.ArrayList fruits = new System.Collections.ArrayList();
fruits.Add("mango");
fruits.Add("apple");
fruits.Add("lemon");
IEnumerable<string> query = fruits.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit);
//fruits.Add(4);
//fruits.Add(2);
//fruits.Add(3);
//IEnumerable<int> query = fruits.Cast<int>().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 (int fruit in query)
//{
// Console.WriteLine(fruit);
//}
//****************************************************************************** Demo Concat
//ConcatEx1();
//****************************************************************************** Demo Count
//ContainsTest();
//ContainsTestForClass();
//****************************************************************************** Demo Contains
//CountEx2();
//****************************************************************************** Demo DefaultIfEmpty
//DefaultIfEmptyEx1();
//DefaultIfEmptyEx2();
//****************************************************************************** Demo ElementAt
//ElementAtTest();
//****************************************************************************** Demo DefaultIfEmpty
//EmptyTest();
//****************************************************************************** Demo ExceptTest
//ExceptTest();
//****************************************************************************** Demo FirstTest
//FirstTest();
//****************************************************************************** Demo FirstTest
AsEnumerableEx1();
//LinQTest();
Console.ReadLine();
}
public static void Test()
{
DateTime dt = new DateTime();
dt = DateTime.Now;
string str = string.Format(dt.ToString("yyyy/MM/dd hh:mm:ss"));
string str1 = string.Format(dt.ToString("dd MM, yyyy"));
Console.WriteLine(str);
Console.WriteLine(str1);
int a = 2;
//if(a.GetType() == System.Type)
Console.ReadLine();
}
public static void LinQTest()
{
//int[] Number = new[]{3,6,9,10,14,32,31};
//var numQuere = from num in Number
// where (num%2) == 0
// orderby num descending
// select num;
//foreach (var i in numQuere)
//{
// Console.WriteLine(i.ToString() + "; ");
//}
//Console.ReadLine();
int[] number = new int[]{4,3,45,664,64,343,32};
var numberSelect = from num in number
where (num%2) != 0
orderby num descending
select num;
foreach (var i in numberSelect)
{
Console.WriteLine(i);
}
}
public static void FirstTest()
{
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 };
int first = numbers.First(item => item < 10);
Console.WriteLine(first);
}
public static void ExceptTest()
{
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());
foreach (var product in except)
Console.WriteLine(product.Name + " " + product.Code);
}
//TODO:need to be checked
public static void EmptyTest()
{
string[] names1 = { "Hartono, Tommy" };
string[] names2 = { "Adams, Terry", "Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
string[] names3 = { "Solanki, Ajay", "Hoeing, Helge",
"Andersen, Henriette Thaulow",
"Potra, Cristina", "Iallo, Lucio" };
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);
}
}
public static void ElementAtTest()
{
string[] names = { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" };
Random random = new Random(DateTime.Now.Millisecond);
int index = random.Next(0, names.Length);
string name = names.ElementAt(index);
Console.WriteLine("The name chosen at random is '{0}'.", name);
//string[] names =
// { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
// "Hedlund, Magnus", "Ito, Shu" };
//int index = 2;
//string name = names.ElementAtOrDefault(index);
//Console.WriteLine(
// "The name chosen at index {0} is '{1}'.",
// index,
// String.IsNullOrEmpty(name) ? "<no name at this index>" : name);
}
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);
}
}
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("\nName: {0}", pet.Name);
}
}
class PetCount
{
public string Name { get; set; }
public bool Vaccinated { get; set; }
}
public static void CountEx2()
{
PetCount[] pets = { new PetCount { Name="Barley", Vaccinated=true },
new PetCount { Name="Boots", Vaccinated=false },
new PetCount { Name="Whiskers", Vaccinated=false } };
try
{
int number = pets.Count(p => p.Vaccinated);
Console.WriteLine("There are {0} vaccinated animals.", number);
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.");
}
}
public static void DistinctClassTest()
{
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);
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);
}
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
// Custom comparer for the Product class
class 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 null
if (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;
}
}
public static void DistinctTest()
{
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);
}
Console.ReadLine();
}
public static void ContainsTestForClass()
{
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);
}
public static void ContainsTest()
{
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);
}
public static void SelectMany()
{
PetContact[] cats = GetCats();
PetContact[] dogs = GetDogs();
IEnumerable<string> query = new[] { cats.Select(cat => cat.Name), dogs.Select(dog => dog.Name) }
.SelectMany(name => name);
foreach (string name in query)
{
Console.WriteLine(name);
}
}
class PetContact
{
public string Name { get; set; }
public int Age { get; set; }
}
static PetContact[] GetCats()
{
PetContact[] cats = { new PetContact { Name="Barley", Age=8 },
new PetContact { Name="Boots", Age=4 },
new PetContact { Name="Whiskers", Age=1 } };
return cats;
}
static PetContact[] GetDogs()
{
PetContact[] dogs = { new PetContact { Name="Bounder", Age=3 },
new PetContact { Name="Snoopy", Age=14 },
new PetContact { Name="Fido", Age=9 } };
return dogs;
}
public static void ConcatEx1()
{
PetContact[] cats = GetCats();
PetContact[] dogs = GetDogs();
IEnumerable<string> query = cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));
foreach (string name in query)
{
Console.WriteLine(name);
}
}
class Package : IComparable<Package>
{
public string Company { get; set; }
public double Weight { get; set; }
int IComparable<Package>.CompareTo(Package other)
{
double WeightOther = other.Weight;
double WeightThis = this.Weight;
if (WeightOther > WeightThis)
return -1;
if (WeightOther == WeightThis)
return 0;
return 1;
}
}
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(pkg => pkg.Weight);
Console.WriteLine("The total weight of the packages is: {0}", totalWeight);
}
/// <summary>
/// This class implements IComparable to be able to
/// compare one Pet to another Pet.
/// </summary>
class Pet1 : IComparable<Pet1>
{
public string Name { get; set; }
public int 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<Pet1>.CompareTo(Pet1 other)
{
int sumOther = other.Age; //+ other.Name.Length;
int sumThis = this.Age; //+ this.Name.Length;
if (sumOther > sumThis)
return -1;
if (sumOther == sumThis)
return 0;
return 1;
}
}
public static void MaxEx3()
{
Pet1[] pets = { new Pet1 { Name="Barley", Age=8 },
new Pet1 { Name="Boots", Age=4 },
new Pet1 { Name="Whiskers", Age=1 } };
Pet1 max = pets.Max();
Console.WriteLine(
"The 'maximum' animal is {0}.",
max.Name);
}
class Pet2
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet2[] pets = { new Pet2 { Name="Barley", Age=8 },
new Pet2 { Name="Boots", Age=4 },
new Pet2 { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age);
Console.WriteLine("The 'maximum' animal is {0}.", max);
}
class ClsTest<T> : List<T>
{
public IEnumerable<T> Where(Func<T, bool> predicate)
{
Console.WriteLine("this is a test method");
return Enumerable.Where(this, predicate);
}
}
public static void AsEnumerableExtest()
{
ClsTest<string> clstest = new ClsTest<string>() { "ABC", "BCD", "AA", "DD" };
IEnumerable<string> query1 = clstest.Where(item => item.Contains("A"));
foreach (var VARIABLE in query1)
{
Console.WriteLine(VARIABLE);
}
}
// Custom class.
class Clump<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);
}
}
static void AsEnumerableEx1()
{
// 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"));
foreach (var VARIABLE in query1)
{
Console.WriteLine(VARIABLE);
}
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"));
foreach (var VARIABLE in query2)
{
Console.WriteLine(VARIABLE);
}
// 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.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
//Array.FindAll 找出Array里所有满足条件的元素; 判断Array里是否有某个元素
public static void AllEx()
{
// 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"));
Pet[] result = Array.FindAll(pets, pet => pet.Name.StartsWith("B"));
Console.WriteLine(
"{0} pet names start with 'B'.",
allStartWithB ? "All" : "Not all");
foreach (var pet in result)
{
Console.WriteLine(pet.Name + "//" + pet.Age);
}
Console.ReadLine();
}
class Person
{
public string LastName { get; set; }
public Pet[] Pets { get; set; }
}
public static void AnyEx2()
{
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;
IEnumerable<List<Pet>> nametest = from person in people where person.Pets.Any() select person.Pets.ToList();
foreach (var petse in nametest)
{
Console.WriteLine(petse);
}
foreach (string name in names)
{
Console.WriteLine(name);
}
/* This code produces the following output:
Haas
Fakhouri
Philips
*/
}
}
public class Product : IEquatable<Product>
{
public string Name { get; set; }
public int Code { get; set; }
public bool Equals(Product other)
{
//TODO:need to be checked for the method ReferenceEquals
//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;
}
}
}
using System.Collections.Generic;
using System.Linq;
//for the Enumerable Methods
namespace LinQ
{
internal class Program
{
private static void Main(string[] args)
{
//******************************************************************************int Distinct
//DistinctTest();
//******************************************************************************class Distinct
//DistinctClassTest();
******************************************************************************Aggregate
//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);
******************************************************************************Aggregate
//string[] fruits = { "apple", "mango", "orange", "passionfruit", "bananaTest333","grape" };
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.
// ABC => ABC.ToUpper());
//Console.WriteLine(
// "The fruit with the longest name is {0}.",
// longestName);
******************************************************************************
For Array All or Find All function
AllEx();
****************************************************************************** List Any
//List<int> numbers = new List<int> { 1, 2 };
//bool hasElements = numbers.Any();
//Console.WriteLine("The list {0} empty.",
// hasElements ? "is not" : "is");
//****************************************************************************** List Any
//AnyEx2();
//****************************************************************************** AsEnumerableEx1
//AsEnumerableEx1();
//****************************************************************************** IEnumerable
//AsEnumerableExtest();
//****************************************************************************** Average double
//List<int> grades = new List<int> { 78, 92, 100, 37, 81 };
//double average = grades.Average();
//Console.WriteLine("The average grade is {0}.", average);
//****************************************************************************** Average longs
//long?[] longs = { null, 10007L, 37L, 399846234235L };
****************************************************************************** Average decimal
//long?[] longs = { null, 1L, 2L, 3 };
//double? average = longs.Average();
//decimal?[] dec = { null, 1m, 2m, 4m };
//decimal? averageDec = dec.Average();
//Console.WriteLine("The average is {0}.", average);
//Console.WriteLine("The average is {0}.", averageDec);
//****************************************************************************** Average decimal
//string[] numbers = { "10007", "37", "299846234235" };
//double average = numbers.Average(num => Convert.ToInt64(num));
//Console.WriteLine("The average is {0}.", average);
//****************************************************************************** Average double
//string[] numbers = { "10007", "37", "299846234235" };
//double average = numbers.Average(num => Convert.ToInt64(num));
//decimal dec = numbers.Average(num => Convert.ToDecimal(num));
//Console.WriteLine("The average is {0}.", average);
//Console.WriteLine("The average is {0}.", dec);
//****************************************************************************** Average double
//string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" };
//double average = fruits.Average(s => s.Length);
//Console.WriteLine("The average string length is {0}.", average);
//****************************************************************************** Average int
//string[] numbers = { "10007", "37", "299846234235" };
//double average = numbers.Average(num => Convert.ToInt64(num));
//Console.WriteLine("The average is {0}.", average);
//****************************************************************************** Max long
//List<long> longs = new List<long> { 4294967296L, 466855135L, 81125L };
//long max = longs.Max();
//Console.WriteLine("The largest number is {0}.", max);
//****************************************************************************** Min long
//List<long> longs = new List<long> { 4294967296L, 466855135L, 81125L };
//long max = longs.Min();
//Console.WriteLine("The largest number is {0}.", max);
//****************************************************************************** Max long
//MaxEx3();
//MaxEx4();
//****************************************************************************** Sum
//SumEx1();
//****************************************************************************** Take
//int[] grades = { 59, 82, 70, 56, 92, 98, 85 };
//IEnumerable<int> topThreeGrades =
// grades.OrderByDescending(grade => grade).Take(3);
//Console.WriteLine("The top three grades are:");
//foreach (int grade in topThreeGrades)
//{
// Console.WriteLine(grade);
//}
****************************************************************************** Take
//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 } };
//IEnumerable<Package> topPackage = packages.OrderByDescending(package => package.Weight).Take(2);
//foreach (var package in topPackage)
//{
// Console.WriteLine(package.Company);
//}
//****************************************************************************** Select
//
//IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * (x + 1));
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
//foreach (int num in squares)
//{
// Console.WriteLine(num);
//}
//string[] fruits = { "apple", "banana", "mango", "orange",
// "passionfruit", "grape" };
//var query = fruits.Select((fruit, index) => new { index, str = fruit.Substring(0, index) });
//foreach (var obj in query)
//{
// Console.WriteLine("{0}", obj);
//}
****************************************************************************** Demo Cast
//System.Collections.ArrayList fruits = new System.Collections.ArrayList();
fruits.Add("mango");
fruits.Add("apple");
fruits.Add("lemon");
IEnumerable<string> query = fruits.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit);
//fruits.Add(4);
//fruits.Add(2);
//fruits.Add(3);
//IEnumerable<int> query = fruits.Cast<int>().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 (int fruit in query)
//{
// Console.WriteLine(fruit);
//}
//****************************************************************************** Demo Concat
//ConcatEx1();
//****************************************************************************** Demo Count
//ContainsTest();
//ContainsTestForClass();
//****************************************************************************** Demo Contains
//CountEx2();
//****************************************************************************** Demo DefaultIfEmpty
//DefaultIfEmptyEx1();
//DefaultIfEmptyEx2();
//****************************************************************************** Demo ElementAt
//ElementAtTest();
//****************************************************************************** Demo DefaultIfEmpty
//EmptyTest();
//****************************************************************************** Demo ExceptTest
//ExceptTest();
//****************************************************************************** Demo FirstTest
//FirstTest();
//****************************************************************************** Demo FirstTest
AsEnumerableEx1();
//LinQTest();
Console.ReadLine();
}
public static void Test()
{
DateTime dt = new DateTime();
dt = DateTime.Now;
string str = string.Format(dt.ToString("yyyy/MM/dd hh:mm:ss"));
string str1 = string.Format(dt.ToString("dd MM, yyyy"));
Console.WriteLine(str);
Console.WriteLine(str1);
int a = 2;
//if(a.GetType() == System.Type)
Console.ReadLine();
}
public static void LinQTest()
{
//int[] Number = new[]{3,6,9,10,14,32,31};
//var numQuere = from num in Number
// where (num%2) == 0
// orderby num descending
// select num;
//foreach (var i in numQuere)
//{
// Console.WriteLine(i.ToString() + "; ");
//}
//Console.ReadLine();
int[] number = new int[]{4,3,45,664,64,343,32};
var numberSelect = from num in number
where (num%2) != 0
orderby num descending
select num;
foreach (var i in numberSelect)
{
Console.WriteLine(i);
}
}
public static void FirstTest()
{
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 };
int first = numbers.First(item => item < 10);
Console.WriteLine(first);
}
public static void ExceptTest()
{
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());
foreach (var product in except)
Console.WriteLine(product.Name + " " + product.Code);
}
//TODO:need to be checked
public static void EmptyTest()
{
string[] names1 = { "Hartono, Tommy" };
string[] names2 = { "Adams, Terry", "Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
string[] names3 = { "Solanki, Ajay", "Hoeing, Helge",
"Andersen, Henriette Thaulow",
"Potra, Cristina", "Iallo, Lucio" };
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);
}
}
public static void ElementAtTest()
{
string[] names = { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" };
Random random = new Random(DateTime.Now.Millisecond);
int index = random.Next(0, names.Length);
string name = names.ElementAt(index);
Console.WriteLine("The name chosen at random is '{0}'.", name);
//string[] names =
// { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
// "Hedlund, Magnus", "Ito, Shu" };
//int index = 2;
//string name = names.ElementAtOrDefault(index);
//Console.WriteLine(
// "The name chosen at index {0} is '{1}'.",
// index,
// String.IsNullOrEmpty(name) ? "<no name at this index>" : name);
}
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);
}
}
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("\nName: {0}", pet.Name);
}
}
class PetCount
{
public string Name { get; set; }
public bool Vaccinated { get; set; }
}
public static void CountEx2()
{
PetCount[] pets = { new PetCount { Name="Barley", Vaccinated=true },
new PetCount { Name="Boots", Vaccinated=false },
new PetCount { Name="Whiskers", Vaccinated=false } };
try
{
int number = pets.Count(p => p.Vaccinated);
Console.WriteLine("There are {0} vaccinated animals.", number);
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.");
}
}
public static void DistinctClassTest()
{
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);
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);
}
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
// Custom comparer for the Product class
class 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 null
if (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;
}
}
public static void DistinctTest()
{
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);
}
Console.ReadLine();
}
public static void ContainsTestForClass()
{
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);
}
public static void ContainsTest()
{
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);
}
public static void SelectMany()
{
PetContact[] cats = GetCats();
PetContact[] dogs = GetDogs();
IEnumerable<string> query = new[] { cats.Select(cat => cat.Name), dogs.Select(dog => dog.Name) }
.SelectMany(name => name);
foreach (string name in query)
{
Console.WriteLine(name);
}
}
class PetContact
{
public string Name { get; set; }
public int Age { get; set; }
}
static PetContact[] GetCats()
{
PetContact[] cats = { new PetContact { Name="Barley", Age=8 },
new PetContact { Name="Boots", Age=4 },
new PetContact { Name="Whiskers", Age=1 } };
return cats;
}
static PetContact[] GetDogs()
{
PetContact[] dogs = { new PetContact { Name="Bounder", Age=3 },
new PetContact { Name="Snoopy", Age=14 },
new PetContact { Name="Fido", Age=9 } };
return dogs;
}
public static void ConcatEx1()
{
PetContact[] cats = GetCats();
PetContact[] dogs = GetDogs();
IEnumerable<string> query = cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));
foreach (string name in query)
{
Console.WriteLine(name);
}
}
class Package : IComparable<Package>
{
public string Company { get; set; }
public double Weight { get; set; }
int IComparable<Package>.CompareTo(Package other)
{
double WeightOther = other.Weight;
double WeightThis = this.Weight;
if (WeightOther > WeightThis)
return -1;
if (WeightOther == WeightThis)
return 0;
return 1;
}
}
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(pkg => pkg.Weight);
Console.WriteLine("The total weight of the packages is: {0}", totalWeight);
}
/// <summary>
/// This class implements IComparable to be able to
/// compare one Pet to another Pet.
/// </summary>
class Pet1 : IComparable<Pet1>
{
public string Name { get; set; }
public int 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<Pet1>.CompareTo(Pet1 other)
{
int sumOther = other.Age; //+ other.Name.Length;
int sumThis = this.Age; //+ this.Name.Length;
if (sumOther > sumThis)
return -1;
if (sumOther == sumThis)
return 0;
return 1;
}
}
public static void MaxEx3()
{
Pet1[] pets = { new Pet1 { Name="Barley", Age=8 },
new Pet1 { Name="Boots", Age=4 },
new Pet1 { Name="Whiskers", Age=1 } };
Pet1 max = pets.Max();
Console.WriteLine(
"The 'maximum' animal is {0}.",
max.Name);
}
class Pet2
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void MaxEx4()
{
Pet2[] pets = { new Pet2 { Name="Barley", Age=8 },
new Pet2 { Name="Boots", Age=4 },
new Pet2 { Name="Whiskers", Age=1 } };
int max = pets.Max(pet => pet.Age);
Console.WriteLine("The 'maximum' animal is {0}.", max);
}
class ClsTest<T> : List<T>
{
public IEnumerable<T> Where(Func<T, bool> predicate)
{
Console.WriteLine("this is a test method");
return Enumerable.Where(this, predicate);
}
}
public static void AsEnumerableExtest()
{
ClsTest<string> clstest = new ClsTest<string>() { "ABC", "BCD", "AA", "DD" };
IEnumerable<string> query1 = clstest.Where(item => item.Contains("A"));
foreach (var VARIABLE in query1)
{
Console.WriteLine(VARIABLE);
}
}
// Custom class.
class Clump<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);
}
}
static void AsEnumerableEx1()
{
// 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"));
foreach (var VARIABLE in query1)
{
Console.WriteLine(VARIABLE);
}
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"));
foreach (var VARIABLE in query2)
{
Console.WriteLine(VARIABLE);
}
// 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.
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
//Array.FindAll 找出Array里所有满足条件的元素; 判断Array里是否有某个元素
public static void AllEx()
{
// 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"));
Pet[] result = Array.FindAll(pets, pet => pet.Name.StartsWith("B"));
Console.WriteLine(
"{0} pet names start with 'B'.",
allStartWithB ? "All" : "Not all");
foreach (var pet in result)
{
Console.WriteLine(pet.Name + "//" + pet.Age);
}
Console.ReadLine();
}
class Person
{
public string LastName { get; set; }
public Pet[] Pets { get; set; }
}
public static void AnyEx2()
{
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;
IEnumerable<List<Pet>> nametest = from person in people where person.Pets.Any() select person.Pets.ToList();
foreach (var petse in nametest)
{
Console.WriteLine(petse);
}
foreach (string name in names)
{
Console.WriteLine(name);
}
/* This code produces the following output:
Haas
Fakhouri
Philips
*/
}
}
public class Product : IEquatable<Product>
{
public string Name { get; set; }
public int Code { get; set; }
public bool Equals(Product other)
{
//TODO:need to be checked for the method ReferenceEquals
//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;
}
}
}