using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Clipcode.Library.Snippet.Linq { public class EnumerableWithQueryOperators { static public void Run() { Aggregate_Demo(); All_Demo();//<(Of <(TSource>)>) Any_Demo(); AsEnumerable_Demo();//<(Of <(TSource>)>) Average_Demo(); Cast_Demo(); //<(Of <(TResult>)>) Concat_Demo(); //<(Of <(TSource>)>) Contains_Demo(); Count_Demo(); DefaultIfEmpty_Demo(); Distinct_Demo(); ElementAt_Demo(); //<(Of <(TSource>)>) ElementAtOrDefault_Demo(); //<(Of <(TSource>)>) Empty_Demo(); //<(Of <(TResult>)>) Except_Demo(); First_Demo(); FirstOrDefault_Demo(); GroupBy_Demo(); GroupJoin_Demo(); Intersect_Demo(); Join_Demo(); Last_Demo(); LastOrDefault_Demo(); LongCount_Demo(); Max_Demo(); Min_Demo(); OfType_Demo(); //<(Of <(TResult>)>) OrderBy_Demo(); OrderByDescending_Demo(); Range_Demo(); Repeat_Demo(); //<(Of <(TResult>)>) Reverse_Demo(); //<(Of <(TSource>)>) Select_Demo(); SelectMany_Demo(); SequenceEqual_Demo(); Single_Demo(); SingleOrDefault_Demo(); Skip_Demo(); //<(Of <(TSource>)>) SkipWhile_Demo(); Sum_Demo(); Take_Demo(); //<(Of <(TSource>)>) TakeWhile_Demo(); ThenBy_Demo(); ThenByDescending_Demo(); ToArray_Demo(); //<(Of <(TSource>)>) ToDictionary_Demo(); ToList_Demo(); //<(Of <(TSource>)>) ToLookup_Demo(); Union_Demo(); Where_Demo(); Zip_Demo(); } static void Aggregate_Demo() { Int32[] numbers = new Int32[] {1,2,3,4,5,6,7,8,9, 0}; var x = numbers.Aggregate((num, next) => next+num); // could also be achieved with Sum } static void All_Demo()//<(Of <(TSource>)>) { Char[] letters = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Boolean allLettersAreEarlyInAlphabet = letters.All(letter => letter < 'h'); Boolean allLettersAreVeryEarlyInAlphabet = letters.All(letter => letter < 'd'); Console.WriteLine("allLettersAreEarlyInAlphabet is " + allLettersAreEarlyInAlphabet.ToString()); Console.WriteLine("allLettersAreVeryEarlyInAlphabet is " + allLettersAreVeryEarlyInAlphabet.ToString()); } static void Any_Demo() { Char[] letters = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Boolean atLeastOneLetterIsEarlyInAlphabet = letters.Any(letter => letter < 'c'); Console.WriteLine("atLeastOneLetterIsEarlyInAlphabet is " + atLeastOneLetterIsEarlyInAlphabet.ToString()); } class MyEnum : Stack { public IEnumerable Where(Func predicate) { Console.WriteLine("In altered where"); return Enumerable.Where(this, predicate); } } static void AsEnumerable_Demo() //<(Of <(TSource>)>) { MyEnum myStack = new MyEnum(); myStack.Push(4); myStack.Push(54); myStack.Push(421); // MyEnum.Where called IEnumerable result = myStack.Where(myNum => myNum > 10); // General Enumerable.Where called IEnumerable otherResult = myStack.AsEnumerable().Where(myNum => myNum > 10); } static void Average_Demo() { Int32[] numbers = new Int32[] { 1, 2, 3, 4, 5, 6 }; double avgOfAllItems = numbers.Average(); Snippets.WriteResult("Average of ints is " + avgOfAllItems.ToString()); } static void Cast_Demo() //<(Of <(TResult>)>) { System.Collections.Stack myNumbers = new Stack(); myNumbers.Push(1); myNumbers.Push(5); myNumbers.Push(11); var result = myNumbers.Cast().Sum(); Console.WriteLine("result = " + result.ToString()); } static void Concat_Demo() //<(Of <(TSource>)>) { Char[] charList1 = new Char[] { 'a', 'f', 'b', 'e', 'd' }; Char[] charList2 = new Char[] { 'a', 'b', 'e', 'c', 'd' }; IEnumerable charList3 = charList1.Concat(charList2); foreach (Char ch in charList3) Snippets.WriteResult(ch); } static void Contains_Demo() { Char[] chars = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Boolean containsE = chars.Contains('e'); Boolean containsZ = chars.Contains('Z'); Console.WriteLine("containsE = " + containsE.ToString() + "; containsZ = " + containsZ.ToString()); } static void Count_Demo() { Char[] chars = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Int32 countOfAllItems = chars.Count(); Int32 countOfItemsGrtC = chars.Count(x => x > 'c'); Snippets.WriteResult( "countOfAllItems = " + countOfAllItems.ToString() + "; countOfItemsGreaterThanC = " + countOfItemsGrtC.ToString()); } static void DefaultIfEmpty_Demo() { Stack letters = new Stack(); Char ch = letters.DefaultIfEmpty().First(); // gets the default character (0) } static void Distinct_Demo() { Char[] charList = new Char[] { 'a', 'f', 'a', 'e', 'e', 'd' }; var distinctChars = charList.Distinct(); } static void ElementAt_Demo() //<(Of <(TSource>)>) { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; var CharAtElement2 = charList.ElementAt(2); // returns third element (b) } static void ElementAtOrDefault_Demo() //<(Of <(TSource>)>) { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; var CharAtElement20OrDefault = charList.ElementAtOrDefault(20); // returns default element (0) } static void Empty_Demo() //<(Of <(TResult>)>) { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; var x = Enumerable.Empty(); x.Union(charList); } static void Except_Demo() { Char[] charList1 = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Char[] charList2 = new Char[] { 'a', 'e', 'c' }; var charList3 = charList1.Except(charList2); } static void First_Demo() { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Char ch = charList.First(); Snippets.WriteResult("First entry = " + ch); ch = charList.First(i => i > 'c'); Snippets.WriteResult("First entry > c = " + ch); } static void FirstOrDefault_Demo() { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Char ch = charList.FirstOrDefault(i => i > 'j'); if (ch == 0) // default Snippets.WriteResult("FirstOrDefault returned default char"); else Snippets.WriteResult("First entry > j = " + ch); } public class City { public String CityTitle; public String Country; public City(String cityTitle, String country) { CityTitle = cityTitle; Country = country; } } public class Landmark { public String LandmarkName; public City Location; } static void GroupBy_Demo() { List cities = new List { new City("San Francisco", "USA"), new City("London", "England"), new City("Tokyo", "Japan"), new City("Manchester", "England"), new City("Atlanta", "USA") }; var result = cities.GroupBy(city => city.Country, city => city.CityTitle); foreach (var group in result) { Console.WriteLine("Group key = " + group.Key); foreach (String cityTitle in group) Console.WriteLine(" " + cityTitle); } /* Output is: Group key = USA San Francisco Atlanta Group key = England London Manchester Group key = Japan Tokyo */ } static void GroupJoin_Demo() { City sanFran = new City("San Francisco", "USA"); City london = new City("London", "England"); City atlanta = new City("Atlanta", "USA"); City tokyo = new City("Tokyo", "Japan"); City manchester = new City("Manchester", "England"); List cities = new List { sanFran, tokyo, manchester, atlanta}; List landmarks = new List { new Landmark { LandmarkName = "Golden Gate Bridge", Location = sanFran }, new Landmark { LandmarkName = "Big Ben", Location = london}, new Landmark { LandmarkName = "Centennial Olympic Stadium", Location = atlanta}, new Landmark { LandmarkName = "Akihabara", Location = tokyo}, new Landmark { LandmarkName = "St. Paul's Cathedral", Location = london}, new Landmark { LandmarkName = "Manchester Velodrome", Location = manchester}, new Landmark { LandmarkName = "Alcatraz Island", Location = sanFran } }; var result = cities.GroupJoin(landmarks, city => city, landmark => landmark.Location, (city, myLandmarks) => new { CityName = city.CityTitle, CityLandmarks = myLandmarks.Select(x => x) }); foreach (var destination in result) { Console.WriteLine("cityName = " + destination.CityName); foreach (var landmark in destination.CityLandmarks) Console.WriteLine("landmark = " + landmark.LandmarkName); } } static void Intersect_Demo() { Char[] charList1 = new Char[] { 'a', 'f', 'b', 'e', 'd' }; Char[] charList2 = new Char[] { 'a', 'b', 'e', 'c', 'd' }; IEnumerable charList3 = charList1.Intersect(charList2); foreach (Char ch in charList3) Snippets.WriteResult(ch); } static void Join_Demo() { City sanFran = new City("San Francisco", "USA"); City london = new City("London", "England"); City atlanta = new City("Atlanta", "USA"); City tokyo = new City("Tokyo", "Japan"); City manchester = new City("Manchester", "England"); List cities = new List { sanFran, tokyo, manchester, atlanta}; List landmarks = new List { new Landmark { LandmarkName = "Golden Gate Bridge", Location = sanFran }, new Landmark { LandmarkName = "Big Ben", Location = london}, new Landmark { LandmarkName = "Centennial Olympic Stadium", Location = atlanta}, new Landmark { LandmarkName = "Akihabara", Location = tokyo}, new Landmark { LandmarkName = "St. Paul's Cathedral", Location = london}, new Landmark { LandmarkName = "Manchester Velodrome", Location = manchester}, new Landmark { LandmarkName = "Alcatraz Island", Location = sanFran } }; var result = cities.Join(landmarks, city => city, landmark => landmark.Location, (city, landmark) => new { CityName = city.CityTitle, LandmarkTitle = landmark.LandmarkName, CountryTitle = city.Country }); foreach (var destination in result) { Console.WriteLine("cityName = " + destination.CityName + "; LandmarkTitle = " + destination.LandmarkTitle + "; CountryTitle = " + destination.CountryTitle); } } static void Last_Demo() { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Char ch = charList.Last(); Snippets.WriteResult("Last entry = " + ch); ch = charList.Last(i => i < 'c'); Snippets.WriteResult("Last entry < c = " + ch); } static void LastOrDefault_Demo() { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Char ch = charList.LastOrDefault(i => i > 'j'); if (ch == 0) // default Snippets.WriteResult("LastOrDefault returned default char"); else Snippets.WriteResult("last entry > j = " + ch); } static void LongCount_Demo() { Char[] chars = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; Int64 countOfAllItems = chars.LongCount(); Int64 countOfItemsGrtC = chars.LongCount(x => x > 'c'); Snippets.WriteResult( "countOfAllItems = " + countOfAllItems.ToString() + "; countOfItemsGreaterThanC = " + countOfItemsGrtC.ToString()); } static void Max_Demo() { // With no selector Int32[] numbers = new Int32[] { 1, 2, 3, 4, 5, 6 }; Int32 maxNum = numbers.Max(); // with Selector SampleData[] data = SampleData.GenerateSampleData(); Int32 maxX = data.Max(i => i.x); Snippets.WriteResult("maxX = " + maxX); String maxY = data.Max(i => i.y); Snippets.WriteResult("maxY = " + maxY); } static void Min_Demo() { // With no selector Int32[] numbers = new Int32[] { 1, 2, 3, 4, 5, 6 }; Int32 minNum = numbers.Min(); // with Selector SampleData[] data = SampleData.GenerateSampleData(); Int32 minX = data.Min(i => i.x); Snippets.WriteResult("minX = " + minX); String minY = data.Min(i => i.y); Snippets.WriteResult("minY = " + minY); } public class Cat { public String CatName; public Int32 CatAge; } static void OfType_Demo() //<(Of <(TResult>)>) { ArrayList myItems = new ArrayList { 1, "dog", new Cat { CatName = "Felix", CatAge = 2 }, 4655, new Cat { CatName = "rex", CatAge = 3 }}; var results = myItems.OfType().Where(cat => cat.CatAge > 2); Console.WriteLine("Found cats:"); foreach (Cat c in results) Console.WriteLine(c.CatName); } static void OrderBy_Demo() { City sanFran = new City("San Francisco", "USA"); City london = new City("London", "England"); City atlanta = new City("Atlanta", "USA"); City tokyo = new City("Tokyo", "Japan"); City manchester = new City("Manchester", "England"); List cities = new List { sanFran, tokyo, manchester, atlanta }; var results = cities.OrderBy(city => city.CityTitle); foreach (City c in results) Console.WriteLine(c.CityTitle); } static void OrderByDescending_Demo() { City sanFran = new City("San Francisco", "USA"); City london = new City("London", "England"); City atlanta = new City("Atlanta", "USA"); City tokyo = new City("Tokyo", "Japan"); City manchester = new City("Manchester", "England"); List cities = new List { sanFran, tokyo, manchester, atlanta }; var results = cities.OrderByDescending(city => city.CityTitle); foreach (City c in results) Console.WriteLine(c.CityTitle); } static void Range_Demo() { IEnumerable numbers = Enumerable.Range(30, 40); // fills a list with integers between 30 and 69 foreach (Int32 i in numbers) Console.Write(i.ToString() + "; "); Console.WriteLine(""); } static void Repeat_Demo() //<(Of <(TResult>)>) { IEnumerable numbers = Enumerable.Repeat(30, 40); // fills a list with 40 integers, each of which is 30 foreach (Int32 i in numbers) Console.Write(i.ToString() + "; "); Console.WriteLine(""); } static void Reverse_Demo() //<(Of <(TSource>)>) { Int32[] numbers = new Int32[]{ 3, 7, 31, 4 }; var reversedNumbers = numbers.Reverse(); // note: original collection not altered foreach (Int32 i in reversedNumbers) Console.Write(i.ToString() + "; "); Console.WriteLine(""); } static void Select_Demo() { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; IEnumerable intList = charList.Select(i => (Int32)i); foreach (Int32 i in intList) Snippets.WriteResult(i.ToString()); } class FootballTeam { public String TeamName; public List Players; } static void SelectMany_Demo() { FootballTeam[] teams = { new FootballTeam { TeamName="alpha", Players = new List{"John", "Thomas", "Jo"} }, new FootballTeam { TeamName="gamma", Players = new List{"Jools", "Liam", "Helmut"} }, new FootballTeam { TeamName="theta", Players = new List{"Francis", "Hans", "Maurice"} } }; IEnumerable players = teams.SelectMany(team => team.Players); foreach (String player in players) Console.WriteLine(player); } static void SequenceEqual_Demo() { List PlayerTeam1 = new List { "John", "Thomas", "Jo" }; List PlayerTeam2 = new List { "Jools", "Liam", "Helmut" }; if (PlayerTeam1.SequenceEqual(PlayerTeam2)) Console.WriteLine("Lists are equal"); else Console.WriteLine("Lists are not equal"); } static void Single_Demo() { List players = new List { "John" }; string onlyPlayer = players.Single(); // If sequence contains > 1 element, exception is thrown - "Sequence contains more than one element" } static void SingleOrDefault_Demo() { List players = new List { }; string defaultPlayer = players.SingleOrDefault(); } static void Skip_Demo() //<(Of <(TSource>)>) { Char[] chars = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; IEnumerable charsAfterSkip = chars.Skip(3); foreach (Char ch in charsAfterSkip) Snippets.WriteResult(ch); } static void SkipWhile_Demo() { Char[] chars = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; IEnumerable charsAfterSkip = chars.SkipWhile(i => i < 'd'); foreach (Char ch in charsAfterSkip) Snippets.WriteResult(ch); } static void Sum_Demo() { Int32[] numbers = new Int32[] { 1, 2, 3, 4, 5, 6 }; Int32 sumofNum = numbers.Sum(); } static void Take_Demo() //<(Of <(TSource>)>) { Char[] chars = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; IEnumerable charsTake = chars.Take(3); foreach (Char ch in charsTake) Snippets.WriteResult(ch); } static void TakeWhile_Demo() { Char[] chars = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; IEnumerable charsTake = chars.TakeWhile(i => i < 'c'); foreach (Char ch in charsTake) Snippets.WriteResult(ch); charsTake = chars.TakeWhile((i, count) => i < 'h' && count < 4); foreach (Char ch in charsTake) Snippets.WriteResult(ch); } static void ThenBy_Demo() { City sanFran = new City("San Francisco", "USA"); City london = new City("London", "England"); City atlanta = new City("Atlanta", "USA"); City tokyo = new City("Tokyo", "Japan"); City manchester = new City("Manchester", "England"); List cities = new List { sanFran, tokyo, london, manchester, atlanta }; var results = cities.OrderBy(city => city.Country).ThenBy(city => city.CityTitle); foreach (City c in results) Console.WriteLine("Country = " + c.Country + "; CityTitle = " + c.CityTitle); } static void ThenByDescending_Demo() { City sanFran = new City("San Francisco", "USA"); City london = new City("London", "England"); City atlanta = new City("Atlanta", "USA"); City tokyo = new City("Tokyo", "Japan"); City manchester = new City("Manchester", "England"); List cities = new List { sanFran, tokyo, manchester, london, atlanta }; var results = cities.OrderBy(city => city.Country).ThenByDescending(city => city.CityTitle); foreach (City c in results) Console.WriteLine("Country = " + c.Country + "; CityTitle = " + c.CityTitle); } static void ToArray_Demo() //<(Of <(TSource>)>) { Char[] charList1 = new Char[] { 'a', 'f', 'b', 'e', 'd' }; Char[] charList2 = new Char[] { 'a', 'b', 'e', 'c', 'd' }; Char[] chars = charList1.Union(charList2).OrderBy(c=>c).ToArray(); } static void ToDictionary_Demo() { City sanFran = new City("San Francisco", "USA"); City london = new City("London", "England"); City atlanta = new City("Atlanta", "USA"); City tokyo = new City("Tokyo", "Japan"); City manchester = new City("Manchester", "England"); List cities = new List { sanFran, tokyo, london, manchester, atlanta }; var result = cities.ToDictionary(city => city.CityTitle); City c = result["Manchester"]; Console.WriteLine("City = " + c.CityTitle + "; country = " + c.Country); } static void ToList_Demo() //<(Of <(TSource>)>) { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'd' }; List selectedChars = charList.Select(c => c).Where(c => c > 'b').ToList(); } static void ToLookup_Demo() { List cities = new List { new City("San Francisco", "USA"), new City("London", "England"), new City("Tokyo", "Japan"), new City("Manchester", "England"), new City("Atlanta", "USA") }; var result = cities.ToLookup(city => city.Country, city => city.CityTitle); Console.WriteLine("---"); foreach (var group in result) { Console.WriteLine("Group key = " + group.Key); foreach (String cityTitle in group) Console.WriteLine(" " + cityTitle); } } static void Union_Demo() { Char[] charList1 = new Char[] { 'a', 'f', 'b', 'e', 'd' }; Char[] charList2 = new Char[] { 'a', 'b', 'e', 'c', 'd' }; IEnumerable charList3 = charList1.Union(charList2); foreach (Char ch in charList3) Snippets.WriteResult(ch); } static void Where_Demo() { Char[] charList = new Char[] { 'a', 'f', 'b', 'e', 'c', 'd' }; var x = charList.Where(i => i > 'c'); foreach (Char ch in x) Snippets.WriteResult(ch); } static void Zip_Demo() { List boys = new List{ "Albert", "Leroy", "Dieter" }; List girls = new List { "Mary", "Jennifer", "Jane" }; var dancePartners = boys.Zip(girls, (boy, girl) => new {b=boy, g=girl}); } } public class SampleData { public Int32 x { get; private set; } public String y { get; private set; } static public SampleData[] GenerateSampleData() { SampleData[] data = new SampleData[] { new SampleData { x = 4, y = "alpha" } , new SampleData { x = 24, y = "beta" }}; return data; } } }