private static void LINQExtensions() { doubleIt dlIt = x => x * 2; Console.WriteLine($"5 * 2 = {dlIt(5)}"); var numList = new List <int> { 1, 9, 2, 6, 3 }; var evenList = numList.Where(a => a % 2 == 0).ToList(); foreach (var i in evenList) { Console.Write($"{i} "); } Console.WriteLine(); var listOne = new List <int> { 1, 3, 4 }; var listTwo = new List <int> { 4, 6, 8 }; var sumList = listOne.Zip(listTwo, (x, y) => x + y).ToList(); foreach (var i in sumList) { Console.Write($"{i} "); } Console.WriteLine(); var SUM = new List <int> { 1, 2, 3, 4, 5 }.Aggregate((a, b) => a + b); var AVERAGE = new List <int> { 1, 2, 3, 4, 5 }.AsQueryable().Average(); Console.WriteLine(SUM); Console.WriteLine(AVERAGE); }
static void Main(string[] args) { doubleIt dblit = x => x * 2; Console.WriteLine($"5*2 = {dblit(5)}"); List <int> numList = new List <int> { 1, 9, 3, 4, 8, 2, 5 }; var evenList = numList.Where(a => a % 2 == 0).ToList(); foreach (var j in evenList) { Console.WriteLine(j); } var rangeList = numList.Where(x => (x > 2) || (x < 9)).ToList(); foreach (var j in evenList) { Console.WriteLine(j); } Console.Read(); }
static void Main(string[] args) { // Like we did with predicates earlier // Lambda expressions allow you to // use anonymous methods that define // the input parameters on the left // and the code to execute on the right // Assign a Lambda to the delegate doubleIt dblIt = x => x * 2; Console.WriteLine($"5 * 2 = {dblIt(5)}"); // You don't have to use delegates though // Here we'll search through a list to // find all the even numbers List <int> numList = new List <int> { 1, 9, 2, 6, 3 }; // Put the number in the list if the // condition is true var evenList = numList.Where(a => a % 2 == 0).ToList(); foreach (var j in evenList) { Console.WriteLine(j); } // Add values in a range to a list var rangeList = numList.Where(x => (x > 2) || (x < 9)).ToList(); foreach (var k in rangeList) { Console.WriteLine(k); } // Find the number of heads and tails in // a list 1 = H, 2 = T // Generate our list List <int> flipList = new List <int>(); int i = 0; Random rnd = new Random(); while (i < 100) { flipList.Add(rnd.Next(1, 3)); i++; } // Print out the heads and tails Console.WriteLine("Heads : {0}", flipList.Where(a => a == 1).ToList().Count()); Console.WriteLine("Tails : {0}", flipList.Where(a => a == 2).ToList().Count()); // Find all names starting with s var nameList = new List <string> { "Doug", "Sally", "Sue" }; var sNameList = nameList.Where(x => x.StartsWith("S")); foreach (var m in sNameList) { Console.WriteLine(m); } // ---------- SELECT ---------- // Select allows us to execute a function // on each item in a list // Generate a list from 1 to 10 var oneTo10 = new List <int>(); oneTo10.AddRange(Enumerable.Range(1, 10)); var squares = oneTo10.Select(x => x * x); foreach (var l in squares) { Console.WriteLine(l); } // ---------- ZIP ---------- // Zip applies a function to two lists // Add values in 2 lists together var listOne = new List <int>(new int[] { 1, 3, 4 }); var listTwo = new List <int>(new int[] { 4, 6, 8 }); var sumList = listOne.Zip(listTwo, (x, y) => x + y).ToList(); foreach (var n in sumList) { Console.WriteLine(n); } // ---------- AGGREGATE ---------- // Aggregate performs an operation on // each item in a list and carries the // results forward // Sum values in a list var numList2 = new List <int>() { 1, 2, 3, 4, 5 }; Console.WriteLine("Sum : {0}", numList2.Aggregate((a, b) => a + b)); // ---------- AVERAGE ---------- // Get the average of a list of values var numList3 = new List <int>() { 1, 2, 3, 4, 5 }; // AsQueryable allows you to manipulate the // collection with the Average function Console.WriteLine("AVG : {0}", numList3.AsQueryable().Average()); // ---------- ALL ---------- // Determines if all items in a list // meet a condition var numList4 = new List <int>() { 1, 2, 3, 4, 5 }; Console.WriteLine("All > 3 : {0}", numList4.All(x => x > 3)); // ---------- ANY ---------- // Determines if any items in a list // meet a condition var numList5 = new List <int>() { 1, 2, 3, 4, 5 }; Console.WriteLine("Any > 3 : {0}", numList5.Any(x => x > 3)); // ---------- DISTINCT ---------- // Eliminates duplicates from a list var numList6 = new List <int>() { 1, 2, 3, 2, 3 }; Console.WriteLine("Distinct : {0}", string.Join(", ", numList6.Distinct())); // ---------- EXCEPT ---------- // Receives 2 lists and returns values not // found in the 2nd list var numList7 = new List <int>() { 1, 2, 3, 2, 3 }; var numList8 = new List <int>() { 3 }; Console.WriteLine("Except : {0}", string.Join(", ", numList7.Except(numList8))); // ---------- INTERSECT ---------- // Receives 2 lists and returns values that // both lists have var numList9 = new List <int>() { 1, 2, 3, 2, 3 }; var numList10 = new List <int>() { 2, 3 }; Console.WriteLine("Intersect : {0}", string.Join(", ", numList9.Intersect(numList10))); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine(); for (int i = 0; i < args.Length; i++) { Console.WriteLine($"Arg {i}: {args[i]}"); } string[] myArgs = Environment.GetCommandLineArgs(); Console.WriteLine(string.Join(", ", myArgs)); //SayHallo(); bool canIVote = true; Console.WriteLine($"Biggest Integer: {int.MaxValue}"); Console.WriteLine($"Smallest Integer: {int.MinValue}"); Console.WriteLine($"Biggest Double: {double.MaxValue.ToString("#")}"); decimal decPiVal = 3.1315926535897932384626433832M; bool boolFromStr = bool.Parse("true"); int intFromStr = int.Parse("10"); DateTime awesomeDate = new DateTime(1986, 3, 2); Console.WriteLine($"Day of Week: {awesomeDate.DayOfWeek}"); awesomeDate = awesomeDate.AddDays(4); awesomeDate = awesomeDate.AddMonths(1); awesomeDate = awesomeDate.AddYears(2); Console.WriteLine($"New date: {awesomeDate.Date}"); TimeSpan lunchTime = new TimeSpan(12, 30, 0); lunchTime = lunchTime.Subtract(new TimeSpan(0, 15, 0)); lunchTime = lunchTime.Add(new TimeSpan(1, 0, 0)); Console.WriteLine($"New Time: {lunchTime.ToString()}"); BigInteger big = BigInteger.Parse("1234132432543253242342342314122412"); Console.WriteLine($"Big Num * 2 = {big * 2}"); Console.WriteLine("Currency: {0:c}", 23.455); Console.WriteLine("Pad with 0s: {0:d4}", 23); Console.WriteLine("3 Decimals: {0:f3}", 23.4555); Console.WriteLine("Commas: {0:n4}", 2300); string randString = "This is a string"; Console.WriteLine("String Length: {0}", randString.Length); Console.WriteLine("String Contains is: {0}", randString.Contains("is")); Console.WriteLine("Index of is: {0}", randString.IndexOf("is")); Console.WriteLine("Remove String: {0}", randString.Remove(0, 6)); Console.WriteLine("Insert String: {0}", randString.Insert(10, "short ")); Console.WriteLine("Replace String: {0}", randString.Replace("string", "sentence")); Console.WriteLine("Compare A to B: {0}", String.Compare("A", "B", StringComparison.OrdinalIgnoreCase)); Console.WriteLine("A = a: {0}", String.Equals("A", "a", StringComparison.OrdinalIgnoreCase)); Console.WriteLine("Pad Left: {0}", randString.PadLeft(20, '.')); Console.WriteLine("Pad Right: {0}", randString.PadRight(20, '.')); Console.WriteLine("Trim(): {0}", randString.Trim()); Console.WriteLine("Uppercase: {0}", randString.ToUpper()); Console.WriteLine("Lowercase: {0}", randString.ToLower()); string newString = String.Format("{0} saw a {1} {2} in the {3}", "Paul", "rabbit", "eating", "field"); Console.WriteLine(newString); Console.WriteLine(@"Exactly what I Typed ' \"); // Classes Shape[] shapes = { new Circle(5), new Rectangle(4, 5) }; foreach (Shape s in shapes) { s.GetInfo(); Console.WriteLine("{0} Area: {1:f2}", s.Name, s.Area()); Circle testCirc = s as Circle; if (testCirc == null) { Console.WriteLine("This isn't a Circle"); } if (s is Circle) { Console.WriteLine("This isn't a Rectangle"); } } object circ1 = new Circle(4); Circle circ2 = (Circle)circ1; Console.WriteLine("The {0} Area is {1:f2}", circ2.Name, circ2.Area()); // Interfaces Vehicle buick = new Vehicle("Buick", 4, 160); if (buick is IDrivable) { buick.Move(); buick.Stop(); } else { Console.WriteLine("The {0} can't be driven", buick.Brand); } IElectronicDevice TV = TVRemote.GetDevice(); PowerButton powBut = new PowerButton(TV); powBut.Execute(); powBut.Undo(); // Collections collectionFunctions(); // Generics //List<int> numList = new List<int>(); List <Animal> animalList = new List <Animal>(); animalList.Add(new Animal() { Name = "Doug" }); animalList.Add(new Animal() { Name = "Paul" }); animalList.Add(new Animal() { Name = "Sally" }); animalList.Insert(1, new Animal() { Name = "Steve" }); animalList.RemoveAt(1); Console.WriteLine("Num of Animals: {0}", animalList.Count()); foreach (Animal a in animalList) { Console.WriteLine(a.Name); } int x = 5, y = 4; Animal.GetSum(ref x, ref y); string strX = "4", strY = "3"; Animal.GetSum(ref strX, ref strY); Rectangle <int> rec1 = new Rectangle <int>(20, 50); Console.WriteLine(rec1.GetArea()); Rectangle <string> rec2 = new Rectangle <string>("20", "50"); Console.WriteLine(rec2.GetArea()); // Delegates Arithmetic add, sub, addSub; add = new Arithmetic(Add); sub = new Arithmetic(Subtract); addSub = add + sub; Console.WriteLine("Add 6 & 10"); add(6, 10); Console.WriteLine("Add & Subtract 10 & 4"); addSub(10, 4); // Manipulating list doubleIt dlIt = z => z * 2; Console.WriteLine($"5 + 2 = {dlIt(5)}"); List <int> numList = new List <int> { 1, 9, 2, 6, 3 }; var evenList = numList.Where(a => a % 2 == 0).ToList(); foreach (var j in evenList) { Console.WriteLine(j); } var rangeList = numList.Where(a => (a > 2) && (a < 9)).ToList(); foreach (var j in rangeList) { Console.WriteLine(j); } List <int> flipList = new List <int>(); int k = 0; Random rnd = new Random(); while (k < 100) { flipList.Add(rnd.Next(1, 3)); k++; } Console.WriteLine("Heads: {0}", flipList.Where(a => a == 1).ToList().Count); Console.WriteLine("Tails: {0}", flipList.Where(a => a == 2).ToList().Count); var nameList = new List <string> { "Doug", "Sally", "Sue" }; var sNameList = nameList.Where(a => a.StartsWith("S")); foreach (var m in sNameList) { Console.WriteLine(m); } var oneTo10 = new List <int>(); oneTo10.AddRange(Enumerable.Range(1, 10)); var squares = oneTo10.Select(a => a * a); foreach (var l in squares) { Console.WriteLine(l); } var listOne = new List <int>(new int[] { 1, 3, 4 }); var listTwo = new List <int>(new int[] { 4, 6, 8 }); var sumList = listOne.Zip(listTwo, (a, b) => a + b).ToList(); foreach (var n in sumList) { Console.WriteLine(n); } var numList2 = new List <int>() { 1, 2, 3, 4, 5, 6 }; Console.WriteLine("Sum: {0}", numList2.Aggregate((a, b) => a + b)); Console.WriteLine("Average: {0}", numList2.AsQueryable().Average()); Console.WriteLine("All > 3: {0}", numList2.All(a => a > 3)); Console.WriteLine("Any > 3: {0}", numList2.Any(a => a > 3)); var numList3 = new List <int>() { 1, 2, 3, 2, 3 }; Console.WriteLine("Distinct: {0}", string.Join(", ", numList3.Distinct())); var numList4 = new List <int>() { 3 }; Console.WriteLine("Except: {0}", string.Join(", ", numList3.Except(numList4))); Console.WriteLine("Intersect: {0}", string.Join(", ", numList3.Intersect(numList4))); // Overloading and enumaration AnimalFarm myAnimals = new AnimalFarm(); myAnimals[0] = new Animal("Wilbur"); myAnimals[1] = new Animal("Templeton"); myAnimals[2] = new Animal("Gander"); myAnimals[3] = new Animal("Charlotte"); foreach (Animal i in myAnimals) { Console.WriteLine(i.Name); } Box box1 = new Box(2, 3, 4); Box box2 = new Box(5, 6, 7); Box box3 = box1 + box2; Console.WriteLine($"Box 3: {box3}"); Console.WriteLine($"Box Int: {(int)box3}"); Box box4 = (Box)4; Console.WriteLine($"Box 4: {box4}"); var shopkins = new { Name = "Shopkins", Price = 4.99 }; Console.WriteLine("{0} cost ${1}", shopkins.Name, shopkins.Price); var toyArray = new[] { new { Name = "Yo-Kai Pack", Price = 4.99 }, new { Name = "Legos", Price = 9.99 } }; foreach (var item in toyArray) { Console.WriteLine("{0} costs ${1}", item.Name, item.Price); } Console.ReadLine(); }
static void Main(string[] args) { //LAMBDAS doubleIt dblIt = x => x * 2; Console.WriteLine($"5 * 2 = {dblIt(5)}"); //get even numbers List <int> numList = new List <int> { 1, 9, 2, 6, 3 }; var evenList = numList.Where(a => a % 2 == 0).ToList(); foreach (var j in evenList) { Console.Write(j + " "); } Console.WriteLine(); //get range var rangeList = numList.Where(x => (x > 2) && (x < 9)).ToList(); foreach (var j in rangeList) { Console.Write(j + " "); } Console.WriteLine(); //Find number of heads and tails flipped randomly List <int> flipList = new List <int>(); int i = 0; Random rnd = new Random(); while (i < 100) { flipList.Add(rnd.Next(1, 3)); i++; } Console.WriteLine("Heads : {0}", flipList.Where(a => a == 1).ToList().Count()); Console.WriteLine("Tails : {0}", flipList.Where(a => a == 2).ToList().Count()); //Find all names that start with a specific letter var nameList = new List <string> { "Doug", "Sally", "Sue" }; var sNameList = nameList.Where(x => x.StartsWith("S")); foreach (var j in sNameList) { Console.Write(j + " "); } Console.WriteLine(); //SELECT var oneTo10 = new List <int>(); oneTo10.AddRange(Enumerable.Range(1, 10)); var squares = oneTo10.Select(x => x * x); foreach (var j in squares) { Console.Write(j + " "); } Console.WriteLine(); //ZIP var listOne = new List <int>(new int[] { 1, 3, 4 }); var listTwo = new List <int>(new int[] { 4, 6, 8 }); var sumList = listOne.Zip(listTwo, (x, y) => x * 10 + y).ToList(); foreach (var j in sumList) { Console.Write(j + " "); } Console.WriteLine(); //Aggregate var numList2 = new List <int> { 1, 2, 3, 4, 5 }; Console.WriteLine("Sum : {0}", numList2.Aggregate((a, b) => a + b)); //Average Console.WriteLine("Avg: {0}", numList2.AsQueryable().Average()); //All Console.WriteLine("All > 3: {0}", numList2.All(x => x > 3)); //Distinct var numList3 = new List <int> { 1, 2, 3, 2, 3 }; Console.WriteLine("Distint : {0}", string.Join(",", numList3.Distinct())); //Except - takes two lists and returns values that aren't found in the second list var numList4 = new List <int> { 3 }; Console.WriteLine("Except : {0}", string.Join(",", numList3.Except(numList4))); //Intersect - returns values found in both lists Console.WriteLine("Intersect : {0}", string.Join(",", numList3.Intersect(numList4))); }
private static void Part13(string[] args) { #region Lambdas //lambdas let you use anonymous methods that define the input parameters on the left and the code to execute on the right doubleIt dblIt = x => x * 2; Console.WriteLine($"5 * 2 = {dblIt(5)}"); List <int> numList = new List <int>() { 1, 2, 3, 4 }; var evenList = numList.Where(a => a % 2 == 0).ToList(); foreach (var j in evenList) { Console.WriteLine(j); } var rangeList = numList.Where(x => (x > 2) && (x < 9)); foreach (var j in rangeList) { Console.WriteLine(j); } List <int> flipList = new List <int>(); int i = 0; Random rnd = new Random(); while (i < 100) { flipList.Add(rnd.Next(1, 3)); i++; } Console.WriteLine("Heads: {0}", flipList.Where(a => a == 1).ToList().Count()); var nameList = new List <string> { "Bob", "Bobert" }; var sNameList = nameList.Where(x => x.StartsWith("B")); foreach (var m in sNameList) { Console.WriteLine(m); } #endregion #region select //select allows us to execute a function on each item in a list var oneToTen = new List <int>(); oneToTen.AddRange(Enumerable.Range(1, 10)); //sets limits on the list var squares = oneToTen.Select(x => x * x); //puts all of oneToTen into squares once modified by the function foreach (var l in squares) { Console.WriteLine(l); } #endregion #region Zip //add values from both lists together var listOne = new List <int>(new int[] { 1, 3, 4 }); var listTwo = new List <int>(new int[] { 4, 6, 8 }); var sumList = listOne.Zip(listTwo, (x, y) => x + y).ToList(); foreach (var n in sumList) { Console.WriteLine(n); } #endregion #region aggregate //performs operation on each value of a list and then carries those results forward var numList2 = new List <int>() { 1, 2, 3, 4, 5 }; Console.WriteLine("sum: {0}", numList2.Aggregate((a, b) => a + b)); #endregion #region average var numList3 = new List <int>() { 1, 2, 3, 4, 5, 3 }; Console.WriteLine("Avg: {0}", numList3.AsQueryable().Average()); #endregion #region all, any, distinct, accept Console.WriteLine("all values greater than three: {0}", numList3.All(x => x > 3)); Console.WriteLine("any values greater than three: {0}", numList3.Any(x => x > 3)); Console.WriteLine("Distinct: {0}", string.Join(", ", numList3.Distinct())); //in first list Console.WriteLine("Except: {0}", string.Join(", ", numList3.Except(numList2))); //not in second list Console.WriteLine("Except: {0}", string.Join(", ", numList3.Intersect(numList2))); //in both lists #endregion }
delegate double doubleIt(double val);//to be referenced as lambda static void Main() { doubleIt dlIt = x => x * 2; Console.WriteLine($"5 * 2 = {dlIt(5)}"); List <int> numList = new List <int> { 1, 2, 3, 5, 6, 78, 87 }; var evenList = numList.Where(a => a % 2 == 0).ToList();//show elements in the List that are even numbers foreach (var j in evenList) { Console.WriteLine(j); } //add values on a range in a LIst var rangeList = numList.Where(x => (x > 2) || (x < 9)).ToList(); foreach (var j in rangeList) { Console.WriteLine(j); } //find the numbers of heads and tails that are fliped randonly //one =head 2= tail List <int> flipList = new List <int>(); int i = 0; Random rnd = new Random(); while (i < 100) { flipList.Add(rnd.Next(1, 3)); i++; } //print it Console.WriteLine("Heads : {0}", flipList.Where(a => a == 1).ToList().Count()); Console.WriteLine("Tail : {0}", flipList.Where(a => a == 2).ToList().Count()); //find all names that start with a specif letter List <string> nameList = new List <string> { "Diogo", "Ronaldo", "Felipe", "Juliano", "Robert" }; var sNameList = nameList.Where(x => x.StartsWith("R")); foreach (var m in sNameList) { Console.WriteLine(m); } //Select -> can execute a function for each item in the list var oneto10 = new List <int>(); oneto10.AddRange(Enumerable.Range(1, 10)); var squares = oneto10.Select(x => x * x); foreach (var m in squares) { Console.WriteLine(m); } //Zip -> Applies a function to two lists var listOne = new List <int>(new int[] { 1, 2, 3 }); var listTwo = new List <int>(new int[] { 4, 6, 8 }); //sum the lists var sumList = listOne.Zip(listTwo, (x, y) => x + y).ToList(); foreach (var m in sumList) { Console.WriteLine(m); } //Aggregate -> do an operation in each item of the list //and carries the result foward var numList2 = new List <int>() { 1, 2, 3, 4, 5 }; Console.WriteLine("Sum : {0}", numList2.Aggregate((a, b) => a + b)); //Averenge (the name say's it all) var NumList3 = new List <int> { 1, 2, 3, 4, 5 }; Console.WriteLine("Averange : {0}", NumList3.AsQueryable().Average()); //ALL -> if all itens in a list meet a specific condition //(if all for example are bigger than 3) //the result is a boolean var numList4 = new List <int> { 1, 2, 3, 4, 5, 6, 7 }; Console.WriteLine("All > 3 : {0}", numList4.All(x => x > 10)); //Any -> checks if ANY of the itens meet the condition //the result is a boolean var numList5 = new List <int> { 1, 2, 3, 4, 5, 6, 7 }; Console.WriteLine("Any > 3 : {0}", numList4.Any(x => x > 3)); //Distinct -> eliminates duplicates var numList6 = new List <int> { 1, 2, 2, 4, 2, 6, 6 }; Console.WriteLine("Distinct : {0}", string.Join(", ", numList6.Distinct())); //Except -> receives 2 lists and return the values not found in the secons list var numList7 = new List <int> { 1, 2, 3, 4, 5, 6, 7 }; var numList8 = new List <int> { 1 }; Console.WriteLine("Except : {0}", string.Join(", ", numList7.Except(numList8))); //Intersect -> return values that both lists have var numList9 = new List <int> { 1, 2, 3, 4, 5, 6, 7 }; var numList10 = new List <int> { 1, 7 }; Console.WriteLine("Intersect : {0}", string.Join(", ", numList7.Intersect(numList10))); //function to stop to close terminal Console.ReadLine( ); }
static void Main(string[] args) { doubleIt doubleIt = x => x * 2; Console.WriteLine($"5 * 2 = {doubleIt(5)}"); List <int> numList = new List <int> { 1, 9, 2, 6, 3 }; var evenList = numList.Where(a => a % 2 == 0).ToList(); // foreach (var j in evenList) // { // Console.WriteLine(j); // } var rangeList = numList.Where(x => (x > 2 && (x < 9))).ToList(); foreach (var j in rangeList) { Console.WriteLine(j); } List <int> flipList = new List <int>(); int i = 0; Random random = new Random(); while (i < 100) { flipList.Add(random.Next(1, 3)); i++; } Console.WriteLine("Heads : {0}", flipList.Where(a => a == 1).ToList().Count); Console.WriteLine("Tails : {0}", flipList.Where(a => a == 2).ToList().Count); var nameList = new List <string> { "Doug", "Sally", "Sue" }; var sNameList = nameList.Where(x => x.StartsWith("S")); foreach (var m in sNameList) { Console.WriteLine(m); } var oneTo10 = new List <int>(); oneTo10.AddRange(Enumerable.Range(1, 10)); var squares = oneTo10.Select(x => x * x); foreach (var l in squares) { Console.WriteLine(l); } var listOne = new List <int>(new int[] { 1, 3, 4 }); var lisTwo = new List <int>(new int[] { 4, 6, 8 }); var sumList = listOne.Zip(lisTwo, (x, y) => x + y).ToList(); foreach (var n in sumList) { Console.WriteLine(n); } var numList2 = new List <int>() { 1, 2, 3, 4, 5, 3 }; var numList4 = new List <int>() { 3, 2 }; Console.WriteLine("Sum : {0}", numList2.Aggregate((a, b) => a + b)); Console.WriteLine("Average : {0}", numList2.AsQueryable().Average()); Console.WriteLine("All > 3 : {0}", numList2.All(x => x > 3)); Console.WriteLine("Any > 3 : {0}", numList2.Any(x => x > 3)); Console.WriteLine("Distinct : {0}", string.Join(", ", numList2.Distinct())); Console.WriteLine("Except : {0}", string.Join(", ", numList2.Except(numList4))); }
static void Main(string[] args) { // lambda expression define input parameters on the left and perform an opration on the right doubleIt dblIt = x => x * 2; Console.WriteLine($" 5 * 2 = {dblIt(5)}"); List <int> numList = new List <int> { 1, 9, 2, 6, 3 }; var evenList = numList.Where(a => a % 2 == 0).ToList(); foreach (var e in evenList) { Console.WriteLine($"Even List: {e}"); } var rangeList = numList.Where(x => (x > 2) && (x < 9)).ToList(); foreach (var e in rangeList) { Console.WriteLine($"Range List: {e}"); } List <int> flipList = new List <int>(); int i = 0; Random rnd = new Random(); while (i < 100) { flipList.Add(rnd.Next(1, 3)); i++; } Console.WriteLine("Heads : {0}", flipList.Where(a => a == 1).ToList().Count); Console.WriteLine("Tails : {0}", flipList.Where(a => a == 2).ToList().Count); var nameList = new List <string> { "Doug", "Bob", "Sally", "Sue", "Luke", "Derrek", "Josh", "Sam", "Travis" }; Console.WriteLine("Number of names that start with S : {0}", nameList.Where(a => a.StartsWith("S")).ToList().Count); // select allows us to run a function on each item in a list var oneTo10 = new List <int>(); oneTo10.AddRange(Enumerable.Range(1, 10)); var squares = oneTo10.Select(x => x * x); foreach (var square in squares) { Console.WriteLine(square); } // zip applies a function to two lists var listOne = new List <int>(new int[] { 1, 3, 4 }); var listTwo = new List <int>(new int[] { 4, 6, 8 }); var sumList = listOne.Zip(listTwo, (x, y) => x + y).ToList(); foreach (var sum in sumList) { Console.WriteLine(sum); } // aggregate performs operation on each item in a list and carrys it forward var numList2 = new List <int>() { 1, 2, 3, 4, 5 }; Console.WriteLine("Sum: {0}", numList2.Aggregate((x, y) => x + y)); var numList3 = new List <int>() { 1, 2, 3, 4, 5 }; Console.WriteLine("Avg : {0}", numList3.AsQueryable().Average()); // Asks a check if all values in list are greater than 3 Console.WriteLine("All > 3 : {0}", numList3.All(x => x > 3)); // Asks a check if any value is greater than 3 Console.WriteLine("Any > 3 : {0}", numList3.Any(x => x > 3)); // Distinct returns a list with only distinct values var numList4 = new List <int>() { 1, 2, 3, 2, 3 }; Console.WriteLine("Distinct : {0}", string.Join(", ", numList4.Distinct())); // Except takes two lists and returns a list where values in the 2nd list are not found in the 1st list. var numList5 = new List <int>() { 3 }; Console.WriteLine("Except: {0}", string.Join(", ", numList4.Except(numList5))); // Intersect returns only a list where the values are found in both lists. Console.WriteLine("Intersect: {0}", string.Join(", ", numList4.Intersect(numList5))); Console.ReadLine(); }
static void Main(string[] args) { //WHERE() doubleIt dblIt = x => x * 2; Console.WriteLine($"5 * 2 = {dblIt(5)}"); List <int> numList = new List <int> { 1, 9, 6, 4 }; var eveList = numList.Where(a => a % 2 == 0).ToList(); Console.WriteLine("-----------"); var rangeList = numList.Where(x => (x > 2) && (x < 9)).ToList(); foreach (var item in rangeList) { Console.WriteLine(item); } Console.WriteLine("-----------"); List <int> flipList = new List <int>(); Random random = new Random(); for (int i = 0; i < 100; i++) { flipList.Add(random.Next(1, 3)); } Console.WriteLine("Heads : {0}", flipList.Where(a => a == 1).ToList().Count()); Console.WriteLine("Tails : {0}", flipList.Where(a => a == 2).ToList().Count()); Console.WriteLine("-----------"); var nameList = new List <string> { "Doug", "Sally", "Sue" }; var sNameList = nameList.Where(x => x.StartsWith("S")); foreach (var item in sNameList) { Console.WriteLine(item); } Console.WriteLine("-----------"); // SELECT() var oneToTen = new List <int>(); oneToTen.AddRange(Enumerable.Range(1, 10)); var squares = oneToTen.Select(x => x * x); foreach (var item in squares) { Console.WriteLine(item); } Console.WriteLine("-----------"); //ZIP() List <int> listOne = new List <int>(new int[] { 1, 3, 4 }); List <int> listTwo = new List <int>(new int[] { 4, 6, 7 }); var sumList = listOne.Zip(listTwo, (x, y) => x + y); foreach (var item in sumList) { Console.WriteLine(item); } Console.WriteLine("-----------"); //AGGREGATE() var numListTwo = new List <int>() { 1, 2, 3, 4, 5, 4, 3 }; Console.WriteLine("Sum : {0}", numListTwo.Aggregate((a, b) => a + b)); //AVERAGE() Console.WriteLine("Avg : {0}", numListTwo.AsQueryable().Average()); //All() and ANY() Console.WriteLine("All > 3 : {0}", numList.All(x => x > 3)); Console.WriteLine("Any > 3 : {0}", numList.Any(x => x > 3)); //DISTINCT() Console.WriteLine("Distinct : {0}", string.Join(",", numList.Distinct())); //EXCEPT() Console.WriteLine("Except : {0}", string.Join(",", listOne.Except(listTwo))); //INTERSECT() Console.WriteLine("Interesect : {0}", string.Join(",", listOne.Intersect(listTwo))); }
public static void Main(string[] args) { #region Lambda example doubleIt dblIt = x => x * 2; Console.WriteLine($"5 * 2 = {dblIt ( 5 )}"); List <int> numList = new List <int> { 1, 9, 2, 4, 6, 8, 2, 3 }; var evenList = numList.Where(a => a % 2 == 0).ToList( ); var rangeList = numList.Where(x => (x > 2) && (x < 9)).ToList( ); foreach (var r in rangeList) { Console.WriteLine(r); } #endregion #region while/where lambda example List <int> flipList = new List <int> ( ); int i = 0; Random random = new Random( ); while (i < 100) { flipList.Add(random.Next(1, 3)); i++; } Console.WriteLine("Heads: {0}", flipList.Where(a => a == 1).ToList().Count()); Console.WriteLine("Tails: {0}", flipList.Where(a => a == 2).ToList( ).Count( )); var nameList = new List <string> { "Doug", "Sara", "Sue" }; var sNameList = nameList.Where(x => x.StartsWith("S")); foreach (var s in sNameList) { Console.WriteLine(s); } #endregion #region select example var oneToTen = new List <int> ( ); oneToTen.AddRange(Enumerable.Range(1, 10)); var squares = oneToTen.Select(x => x * x); foreach (var s in squares) { Console.WriteLine(s); } #endregion #region zip example var listOne = new List <int> (new int[] { 1, 2, 3, 4, }); var listTwo = new List <int> (new int[] { 5, 6, 7, 8 }); var sumList = listOne.Zip(listTwo, (x, y) => x + y).ToList( ); foreach (var s in sumList) { Console.WriteLine(s); } #endregion #region aggregate example var numList2 = new List <int> ( ) { 1, 2, 3, 4, 5 }; Console.WriteLine("Sum : {0} ", numList2.Aggregate((a, b) => a + b)); #endregion #region average example var numList3 = new List <int> ( ) { 1, 3, 5, 7, 9 }; Console.WriteLine("Average : {0}", numList3.AsQueryable().Average()); #endregion #region if all/any example var numList4 = new List <int> ( ) { 1, 3, 5, 7, 9 }; Console.WriteLine("All > 3: {0}", numList4.All(x => x > 3)); Console.WriteLine("Any > 3: {0}", numList4.Any(x => x > 3)); #endregion #region distinct example var numList5 = new List <int> ( ) { 1, 2, 3, 3, 2, 1 }; Console.WriteLine("Distinct: {0} ", string.Join(" , ", numList5.Distinct())); #endregion #region except example var numList6 = new List <int> ( ) { 1, 3, 5, 7 }; var numList7 = new List <int> ( ) { 3, 7 }; Console.WriteLine(" Except : {0}", string.Join(" , ", numList6.Except(numList7))); #endregion #region intersect example var numList8 = new List <int> ( ) { 1, 3, 5, 7 }; var numList9 = new List <int> ( ) { 3, 7 }; Console.WriteLine(" Intersect : {0}", string.Join(" , ", numList6.Intersect(numList7))); #endregion Console.ReadLine(); CreateWebHostBuilder(args).Build( ).Run( ); }
static void Main(string[] args) { #region Basics // Example Single-line Comment /* Example * Multiline * Comment */ //Hello World Console.WriteLine("Hello World"); //Get user input Console.Write("What's your name? "); string name = Console.ReadLine(); Console.WriteLine("Hello " + name); //Data Types bool canVote = true; char fumoffu = '%'; int maxInt = int.MaxValue; long maxLong = long.MaxValue; decimal maxDecimal = decimal.MaxValue; float maxFloat = float.MaxValue; double maxDouble = double.MaxValue; Console.WriteLine("Max Int: " + maxInt); //Implicit type variable declaration var sampleVar = "SampleString"; //You can't change its type after declaration though //sampleVar = 2; Console.WriteLine("sampleVar is a {0}", sampleVar.GetTypeCode()); Console.WriteLine("-------------------------------------------------------"); //Arithmetics Console.WriteLine("5 + 3 = " + (5 + 3)); Console.WriteLine("5 - 3 = " + (5 - 3)); Console.WriteLine("5 * 3 = " + (5 * 3)); Console.WriteLine("5 / 3 = " + (5 / 3)); Console.WriteLine("5.2 % 3 = " + (5.2 % 3)); int i = 0; Console.WriteLine("i++ = " + i++); Console.WriteLine("++i = " + ++i); Console.WriteLine("i-- = " + i--); Console.WriteLine("--i = " + --i); Console.WriteLine("-------------------------------------------------------"); //Some Math Static Functions //acos, asin, atan, atan2, cos, cosh, exp, log, sin, sinh, tan, tanh double num1 = 10.5; double num2 = 15; Console.WriteLine("Abs(num1): " + Math.Abs(num1)); Console.WriteLine("Ceiling(num1): " + Math.Ceiling(num1)); Console.WriteLine("Floor(num1): " + Math.Floor(num1)); Console.WriteLine("Max(num1, num2): " + Math.Max(num1, num2)); Console.WriteLine("Min(num1, num2): " + Math.Min(num1, num2)); Console.WriteLine("Pow(num1): " + Math.Pow(num1, num2)); Console.WriteLine("Round(num1): " + Math.Round(num1)); Console.WriteLine("Sqrt(num1): " + Math.Sqrt(num1)); Console.WriteLine("-------------------------------------------------------"); //Casting const double PI = 3.14; int intPI = (int)PI; //Generating Random Numbers Random rand = new Random(); Console.WriteLine("Random number between 1 and 10: " + rand.Next(1, 11)); #endregion #region Conditionals and Loops //Relational Operators: > < >= <= == != //Logical Operators: && (AND) || (OR) ^ (XOR) ! (NOT) int age = rand.Next(1, 101); Console.WriteLine(age); //IF statements if (age >= 5 && age <= 7) { Console.WriteLine("Go to Elementary School"); } else if (age > 7 && age < 13) { Console.WriteLine("Go to Middle School"); } else { Console.WriteLine("Go to High School"); } if (age < 14 || age > 67) { Console.WriteLine("You Shouldn't Work"); } Console.WriteLine("! true: " + !true); //Ternary - Condition ? ifTrue : ifFalse bool canDrive = age >= 18 ? true : false; switch (age) { case 0: Console.WriteLine("Infant"); break; case 1: case 2: Console.WriteLine("Toddler"); //Goto jumps to the code block you specify (It's gonna kick you out of the switch statement) goto Checkpoint1; default: Console.WriteLine("Child"); break; } Checkpoint1: Console.WriteLine("I'm printed from outside the switch statement"); Console.WriteLine("-------------------------------------------------------"); int j = 0; while (j < 10) { if (j == 7) { j++; continue; } //^^^ Jump back to the while header if (j == 9) { break; } //// ^^ Jump out of the loop if (j % 2 > 0) { Console.WriteLine(j); } j++; } Console.WriteLine("-------------------------------------------------------"); //DO While: The body of do is executed at least one time string guess; do { Console.WriteLine("Guess a number"); guess = Console.ReadLine(); } while (!guess.Equals("15")); Console.WriteLine("-------------------------------------------------------"); //FOR Loop: All the conditional and counter stuff is in the heading for (int k = 0; k < 10; k++) { if (k % 2 != 0) { Console.WriteLine(k); } } Console.WriteLine("-------------------------------------------------------"); //FOREACH: Used to iterate over list, arrays, maps and collections string randString = "Example Random String"; foreach (char c in randString) { Console.WriteLine(c); } Console.WriteLine("-------------------------------------------------------"); #endregion #region Strings & Arrays //Strings //Escape Sequences: Allow you to enter special chars in strings // \' \" \\ \b \n \t string sampleString = "Some random words"; //Prints wether a string is empty or null Console.WriteLine("Is Empty: " + String.IsNullOrEmpty(sampleString)); //Prints wether a string is null or filled with white space Console.WriteLine("Is Empty: " + String.IsNullOrWhiteSpace(sampleString)); Console.WriteLine("String Length: " + sampleString.Length); //Returns the position of a certain string/char inside of another string | returns -1 if it doesn't find it Console.WriteLine("Index of 'random': " + sampleString.IndexOf("random")); //Returns a substring of the parent string when given the index of the first letter and the length of the word Console.WriteLine("2nd word: " + sampleString.Substring(5, 6)); //Returns true if the parent string is equals to the argument string Console.WriteLine("Strings Equal: " + sampleString.Equals(randString)); //Returns true if the String starts with the argument string Console.WriteLine("Starts with \"Example Random\": " + randString.StartsWith("Example Random")); //Returns true if the String ends with the argument string Console.WriteLine("Ends with \"Example String\": " + randString.EndsWith("Example String")); //Removes white space at the beginning or at the end of a string sampleString = sampleString.Trim(); //TrimEnd TrimStart //Replaces a substring of the parent string with another string sampleString = sampleString.Replace("words", "characters"); //Removes a substring of length equals to the second parameter starting from the passed index (first parameter) sampleString = sampleString.Remove(0, 4); //Array of strings string[] words = new string[6] { "I", "Suck", "At", "Drawing", "Textures", ":(" }; //Join a string array into one single string Console.WriteLine("Joined String Array: " + String.Join(" ", words)); Console.WriteLine("-------------------------------------------------------"); //Formatting Strings string formatted = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 4.99, 15.567, .56, 1000); Console.WriteLine("Formatted Strings examples: " + formatted); Console.WriteLine("-------------------------------------------------------"); //String Builder //Used when you want to edit a string without creating a new one StringBuilder sb = new StringBuilder(); //Append new strings - (AppendLine is the version that appends a \n at the end automatically) sb.Append("This is the first Sentence."); sb.AppendFormat("My Nick is {0} and I am a {1} developer", "Davoleo", "C#"); //Empties the whole StringBuilder Buffer //sb.Clear(); //Replaces a string with another one in all the occurrences in the StringBuilder sb.Replace("e", "E"); //Removes chars from index 5 (included) to index 7 (excluded) sb.Remove(5, 7); //Converts the StringBuilder to a String and writes it on the console Console.WriteLine(sb.ToString()); Console.WriteLine("-------------------------------------------------------"); //Arrays int[] randArray; int[] randFixedArray = new int[5]; int[] literalArray = { 1, 2, 3, 4, 5 }; //Returns the number of items in the array Console.WriteLine("Array Length: " + literalArray.Length); //Returns the first item of an array Console.WriteLine("First Item: " + literalArray[0]); //Loop through arrays //Classic For loop with array length for (int k = 0; k < literalArray.Length; k++) { Console.WriteLine("{0} : {1}", k, literalArray[k]); } //For Each foreach (int num in literalArray) { Console.WriteLine(num); } //Returns the index of a specific array element Console.WriteLine("Index of 3: " + Array.IndexOf(literalArray, 3)); string[] names = { "Shana", "Alastor", "Wilhelmina", "Decarabia", "Fecor", "Hecate", "Sydonnay" }; //Joins all the items of an array dividing them with a custom separator string nameCollectionString = string.Join(", ", names); names = nameCollectionString.Split(','); //Multidimensional Arrays //Two dimensional empty array of length 5*3 int[,] multArray = new int[5, 3]; //Literal Init int[,] multArray2 = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; foreach (int num in multArray2) { Console.WriteLine(num); } Console.WriteLine("-------------------------------------------------------"); //Lists: Dynamic Arrays List <int> numList = new List <int>(); //Adds a Single item to the list numList.Add(5); numList.Add(15); numList.Add(25); //Adds a range of items to the list (in some kind of collection form) int[] numArray = { 1, 2, 3, 4 }; numList.AddRange(numArray); //Removes All the items in the list //numList.Clear(); //Init a list with an array (aka create a list from an array) List <int> numList2 = new List <int>(numArray); //Insert an item in a specific index numList.Insert(1, 10); //Removes the first occurance of the argument in the list, from the list numList.Remove(5); //Removes the item at the index 2 numList.RemoveAt(2); for (var l = 0; l < numList.Count; l++) { Console.WriteLine(numList[l]); } //Returns the index of the first occurance of the passed item (returns -1 if it doesn't find any) Console.WriteLine("4 is in index " + numList2.IndexOf(4)); Console.WriteLine("is 5 in the list " + numList.Contains(5)); List <string> stringList = new List <string>(new string[] { "Davoleo", "Matpac", "Pierknight" }); //case insensitive String comparison Console.WriteLine("Davoleo in list " + stringList.Contains("davoleo", StringComparer.OrdinalIgnoreCase)); //Sorts the list alphabetically or numerically depending on the contents numList.Sort(); Console.WriteLine("-------------------------------------------------------"); #endregion #region Exceptions //Exception Handling //Try and Catch Structure try { Console.Write("Divide 10 by "); int num = int.Parse(Console.ReadLine()); Console.WriteLine("10/{0} = {1}", num, 10 / num); } catch (DivideByZeroException e) { Console.WriteLine("Can't divide by 0"); //Prints the name of the exception Console.WriteLine(e.GetType().Name); //Prints a small description of the exception Console.WriteLine(e.Message); //Throws the same exception again //throw e; //Throws another new Exception throw new InvalidOperationException("Operation Failed", e); } catch (Exception e) { //This Catches all the exceptions Console.WriteLine(e.GetType().Name); Console.WriteLine(e.Message); } Console.WriteLine("-------------------------------------------------------"); #endregion #region OOP //Classes and Objects Animal botolo = new Animal(0.5, 6, "Meeer", "Botolo"); Console.WriteLine("{0} says {1}", botolo.Name, botolo.Sound); Console.WriteLine(botolo.ToString()); Console.WriteLine(Animal.GetCount()); Console.WriteLine("-------------------------------------------------------"); //Method Overloading test //This Calls the int version Console.WriteLine("1 + 25 = " + GetSum(1, 25)); //This Calls the double version //Passing parameters in another order Console.WriteLine("7.64 + 9.24 = " + GetSum(num2: 7.64, num1: 9.24)); Console.WriteLine("-------------------------------------------------------"); //Object Initializer - Assigning values to the fields manually Animal epicAnimal = new Animal() { Name = "Grover", Height = 13, Weight = 11, Sound = "GRRR" }; Console.WriteLine(epicAnimal.ToString()); Console.WriteLine("-------------------------------------------------------"); //Polymorphism Shape rect = new Rectangle(5, 8); Shape tri = new Triangle(8, 3); Shape circle = new Circle(5); //Array of different kinds of shapes Shape[] shapeArray = { rect, tri, circle }; foreach (var shape in shapeArray) { shape.LogShapeInfo(); } Console.WriteLine("***"); Console.WriteLine("Rect Area: " + rect.Area()); Console.WriteLine("Tri Area: " + tri.Area()); Console.WriteLine("Circle Area: " + circle.Area()); Console.WriteLine("tri is a Triangle: " + (tri is Triangle)); Console.WriteLine("rect is a Rectangle: " + ((rect as Rectangle) != null)); Console.WriteLine("-------------------------------------------------------"); //Operator Overloading for objects Rectangle combinedRectangle = new Rectangle(6, 10) + (Rectangle)rect; Console.WriteLine("combinedRectangle Area: " + combinedRectangle.Area()); Console.WriteLine("-------------------------------------------------------"); //Interfaces IElettronicDevice TV = TVRemote.GetDevice(); PowerButton powerButton = new PowerButton(TV); powerButton.Execute(); powerButton.Undo(); Console.WriteLine("-------------------------------------------------------"); //Generics - Classes that can be used with any kind of object SimpleMapEntry <int, string> davPass = new SimpleMapEntry <int, string>(333, "Davoleo"); davPass.ShowData(); //Generics work with multiple data types int firstInt = 5, secondInt = 4; GetSum(ref firstInt, ref secondInt); string firstString = firstInt.ToString(); string secondString = secondInt.ToString(); GetSum(ref firstString, ref secondString); Rectangle <int> rect1 = new Rectangle <int>(20, 50); Console.WriteLine(rect1.GetArea()); Rectangle <string> rect2 = new Rectangle <string>("20", "50"); Console.WriteLine(rect2.GetArea()); Console.WriteLine("-------------------------------------------------------"); Temperature waveTemp = Temperature.WARM; switch (waveTemp) { case Temperature.FREEZE: Console.WriteLine("Freezing Temperature"); break; case Temperature.LOW: Console.WriteLine("Low Temperature"); break; case Temperature.WARM: Console.WriteLine("Warm Temperature"); break; case Temperature.HOT: Console.WriteLine("Hot Temperature"); break; case Temperature.SEARING: Console.WriteLine("EPIC Temperature, everything Sublimates"); break; default: Console.WriteLine("Invalid Temperature"); break; } Console.WriteLine("-------------------------------------------------------"); //STRUCTS Customer davoleo = new Customer(); davoleo.createCustomer("Davoleo", 55.80, 111); davoleo.printInfo(); Console.WriteLine("-------------------------------------------------------"); //DELEGATES - Passing methods to other methods as parameters //Anonymous method of type EvaluateExpression EvaluateExpression add = delegate(double n1, double n2) { return(n1 + n2); }; //Direct Delegate Assignment EvaluateExpression substract = (n1, n2) => { return(n1 + n2); }; EvaluateExpression multiply = delegate(double n1, double n2) { return(n1 * n2); }; //Calls both the delegates EvaluateExpression subtractMultuply = substract + multiply; Console.WriteLine("5 + 10 = " + add(5, 10)); Console.WriteLine("5 * 10 = " + multiply(5, 10)); Console.WriteLine("Subtract & Multiply 10 & 4: " + subtractMultuply(10, 4)); //Lamda expressions - Anonymous functions Func <int, int, int> subtract = (x, y) => x - y; Console.WriteLine("5 - 10 = " + subtract.Invoke(5, 10)); List <int> nums = new List <int> { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 }; List <int> oddNumbers = nums.Where((n) => n % 2 == 1).ToList(); foreach (var oddNumber in oddNumbers) { Console.Write(oddNumber + ", "); } Console.WriteLine(); Console.WriteLine("-------------------------------------------------------"); #endregion #region File IO //File I/O //Access the current directory DirectoryInfo dir = new DirectoryInfo("."); DirectoryInfo davDir = new DirectoryInfo(@"C:\Users\Davoleo"); Console.WriteLine("Davoleo path: " + davDir.FullName); Console.WriteLine("Davoleo dir name " + davDir.Name); Console.WriteLine(davDir.Parent); Console.WriteLine(davDir.Attributes); Console.WriteLine(davDir.CreationTime); //Creates a directory Directory.CreateDirectory(@"D:\C#Data"); DirectoryInfo dataDir = new DirectoryInfo(@"D:\C#Data"); //Directory.Delete(@"D:\C#Data"); string dataPath = @"D:\C#Data"; Console.WriteLine("-------------------------------------------------------"); string[] nicks = { "Davoleo", "Matpac", "Pierknight", "gesudio" }; using (StreamWriter writer = new StreamWriter("nicknames.txt")) { foreach (var nick in nicks) { writer.WriteLine(nick); } } using (StreamReader reader = new StreamReader("nicknames.txt")) { string user; while ((user = reader.ReadLine()) != null) { Console.WriteLine(user); } } //Another Way of writing and reading File.WriteAllLines(dataPath + "\\nicknames.txt", nicks); Console.WriteLine(File.ReadAllBytes(dataPath + "\\nicknames.txt").ToString()); FileInfo[] textFiles = dataDir.GetFiles("*.txt", SearchOption.AllDirectories); Console.WriteLine("Matches: {0}" + textFiles.Length); Console.WriteLine(textFiles[0].Name + ", " + textFiles[0].Length); string fileStreamPath = @"D:\C#Data\streamtest.txt"; FileStream stream = File.Open(fileStreamPath, FileMode.Create); string randomString = "This is a random String"; byte[] randomStringByte = Encoding.Default.GetBytes(randString); stream.Write(randomStringByte, 0, randomStringByte.Length); stream.Position = 0; stream.Close(); string binaryPath = @"D:\C#Data\file.dat"; FileInfo datFile = new FileInfo(binaryPath); BinaryWriter binaryWriter = new BinaryWriter(datFile.OpenWrite()); string text = "Random Text"; age = 18; double height = 12398; binaryWriter.Write(text); binaryWriter.Write(age); binaryWriter.Write(height); binaryWriter.Close(); BinaryReader binaryReader = new BinaryReader(datFile.OpenRead()); Console.WriteLine(binaryReader.ReadString()); Console.WriteLine(binaryReader.ReadInt32()); Console.WriteLine(binaryReader.ReadDouble()); #endregion Console.WriteLine("-------------------------------------------------------"); //OOP Game test Warrior maximus = new Warrior("Maximus", 1000, 120, 40); Warrior bob = new Warrior("Bob", 1000, 120, 40); Console.WriteLine("Disabled"); //Battle.StartFight(maximus, bob); Console.WriteLine("-------------------------------------------------------"); //Collections ---- #region ArrayList //You can add different kind of objects ArrayLists ArrayList arrayList = new ArrayList(); arrayList.Add("Bob"); arrayList.Add(43); //Number of items in the arraylist Console.WriteLine("ArrayList Count: " + arrayList.Count); //Capacity is always double the count (?) Console.WriteLine("ArrayList Capacity: " + arrayList.Capacity); ArrayList arrayList2 = new ArrayList(); //Add an array to the ArrayList arrayList2.AddRange(new object[] { "Jeff", "Dave", "Egg", "Edge" }); arrayList.AddRange(arrayList2); //Sort items in natural order arrayList2.Sort(); //Reverse the order of items arrayList2.Reverse(); //Insert some item at a specific index arrayList2.Insert(1, "PI"); //Sub-Arraylist made of some of the items in the original arraylist ArrayList range = arrayList2.GetRange(0, 2); Console.WriteLine("arrayList object ---"); foreach (object o in arrayList) { Console.Write(o + "\t"); } Console.WriteLine(); Console.WriteLine("arrayList2 object ---"); foreach (object o in arrayList2) { Console.Write(o + "\t"); } Console.WriteLine(); Console.WriteLine("range object ----"); foreach (object o in range) { Console.Write(o + "\t"); } Console.WriteLine(); //Remove the item at the 0 index //arrayList2.RemoveAt(0); //Removes the first 2 items starting from index 0 //arrayList2.RemoveRange(0, 2); //Return the index of a specific object - if it doesn't find any it returns -1 Console.WriteLine("Index of Edge: " + arrayList2.IndexOf("Edge")); //Converting ArrayLists to arrays string[] array = (string[])arrayList2.ToArray(typeof(string)); //Converting back to Arraylist ArrayList listFromArray = new ArrayList(array); #endregion Console.WriteLine("-------------------------------------------------------"); #region Dictionary //Stores a list of key-value pairs Dictionary <string, string> langsProjs = new Dictionary <string, string>(); //Add A Key-Value Pair langsProjs.Add("C#", "CSharp-Test"); langsProjs.Add("Java", "Metallurgy 4: Reforged"); langsProjs.Add("Dart", "sample_flutter_app"); //Removes a Pair from a given key langsProjs.Remove("Dart"); //Number of pairs in the list Console.WriteLine("Count: " + langsProjs.Count); //Returns wether a key is present Console.WriteLine("C# is present: " + langsProjs.ContainsKey("C#")); //Gets the value of Java and outputs into a new string called test langsProjs.TryGetValue("Java", out string test); Console.WriteLine("Java: " + test); //Loop over all the pairs in the list Console.WriteLine("LOOP:"); foreach (KeyValuePair <string, string> pair in langsProjs) { Console.WriteLine($"{pair.Key} - {pair.Value}"); } //Empties the dictionary Completely langsProjs.Clear(); #endregion Console.WriteLine("-------------------------------------------------------"); #region Queue //Creates a new Empty Queue Queue queue = new Queue(); //Adds an item to the queue queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); //Loop over a queue foreach (object num in queue) { Console.Write(num + "\t"); } Console.WriteLine(); Console.WriteLine("is 3 in the queue: " + queue.Contains(3)); //Removes the first item and return it to you Console.WriteLine("Removes 1: " + queue.Dequeue()); //Returns the first item in the queue without removing it Console.WriteLine("Peek the firs num: " + queue.Peek()); //Empties the queue queue.Clear(); #endregion Console.WriteLine("-------------------------------------------------------"); #region Stack Stack stack = new Stack(); //Adds an item to the stack stack.Push(1); stack.Push(2); stack.Push(3); stack.Push(4); //Loop over a stack - items are returned in the opposite order foreach (var item in stack) { Console.WriteLine($"Item: {item}"); } //Returns the last item in the stack without removing it Console.WriteLine(stack.Peek()); //Returns the last item in the stack removing it Console.WriteLine(stack.Pop()); //Returns wether the stack contains an item or not Console.WriteLine(stack.Contains(3)); //Convert to an array and print it with the Join function Console.WriteLine(string.Join(", ", stack.ToArray())); //Empties the stack stack.Clear(); #endregion Console.WriteLine("-------------------------------------------------------"); #region LINQ EXTENSION METHODS //LINQ EXTENSION METHODS //Lamdas with Delegates Console.WriteLine("-- Lambda Expressions --"); doubleIt doubleIt = x => x * 2; Console.WriteLine($"5 * 2 = {doubleIt(5)}"); List <int> numberList = new List <int> { 1, 9, 2, 6, 3 }; //.Where() METHOD var evenList = numberList.Where(a => a % 2 == 0).ToList(); foreach (var k in evenList) { Console.Write(k + ", "); } Console.WriteLine(); //2nd Example of .Where() var rangeList = numberList.Where(x => x > 2 && x < 9).ToList(); foreach (var k in rangeList) { Console.Write(k + ", "); } Console.WriteLine(); //Coin flips (T = 0 or C = 1) List <int> coinFlips = new List <int>(); int flips = 0; while (flips < 100) { coinFlips.Add(rand.Next(0, 2)); flips++; } //Count method with predicate Console.WriteLine($"Testa Count: {coinFlips.Count(a => a == 0)}"); Console.WriteLine($"Croce Count: {coinFlips.Count(a => a == 1)}"); //.Select() METHOD var oneToTen = new List <int>(); oneToTen.AddRange(Enumerable.Range(1, 10)); var squares = oneToTen.Select(x => x * x); foreach (var k in squares) { Console.Write(k + ", "); } Console.WriteLine(); //.Zip() METHOD var listOne = new List <int> { 1, 3, 4 }; var listTwo = new List <int> { 4, 6, 8 }; var sumList = listOne.Zip(listTwo, (l1Value, l2Value) => l1Value + l2Value); foreach (var k in sumList) { Console.Write(k + ", "); } Console.WriteLine(); //.Aggregate() METHOD var nums1to5 = new List <int> { 1, 2, 3, 4, 5 }; Console.WriteLine("Sum of elements {0}", nums1to5.Aggregate((a, b) => a + b)); //.AsQueryable.Average() Method Console.WriteLine($"Average: {nums1to5.AsQueryable().Average()}"); //.All() Console.WriteLine($"All > 3 nums? {nums1to5.All(x => x > 3)}"); //.Any() Console.WriteLine($"Any num > 3? {nums1to5.Any(x => x > 3)}"); //.Distinct() var listWithDupes = new List <int> { 1, 2, 3, 2, 3 }; Console.WriteLine($"Distinct: {string.Join(", ", listWithDupes.Distinct())}"); //.Except() - Prints all the values that don't exist in the second list Console.WriteLine($"Except: {string.Join(", ", nums1to5.Except(listWithDupes))}"); //.Intersect() - Returns a list with common values between two lists Console.WriteLine($"Intersect: {string.Join(", ", nums1to5.Intersect(listWithDupes))}"); #endregion Console.WriteLine("-------------------------------------------------------"); #region Custom Collection Class AnimalFarm animals = new AnimalFarm(); animals[0] = new Animal("Wilbur"); animals[1] = new Animal("Templeton"); animals[2] = new Animal("Wally"); animals[3] = new Animal("ooooooooooooooooooooooooeuf"); foreach (Animal animal in animals) { Console.WriteLine(animal.Name); } Box box1 = new Box(2, 3, 4); Box box2 = new Box(5, 6, 7); Box boxSum = box1 + box2; Console.WriteLine($"Box Sum: {boxSum}"); Console.WriteLine($"Box -> Int: {(int) box1}"); Console.WriteLine($"Int -> Box: {(Box) 4}"); //Anonymous type object var anonymous = new { Name = "Mr Unknown", Status = 312 }; Console.WriteLine("{0} status is {1}", anonymous.Name, anonymous.Status); #endregion Console.WriteLine("-------------------------------------------------------"); #region LINQ //Stands for Launguage Integrated Query - Provides tools to work with data QueryStringArray(); QueryIntArray(); QueryArrayList(); QueryCollection(); QueryAnimalData(); #endregion Console.WriteLine("-------------------------------------------------------"); #region Threads //Threading allows to execute operation on a different workflow instead of the Main one //The workflow continuously and quickly changes thread to Thread thread = new Thread(Print1); thread.Start(); for (int k = 0; k < 1000; k++) { Console.Write(0); } Console.WriteLine(); int counter = 1; for (int k = 0; k < 10; k++) { Console.WriteLine(counter); //Slow down the current thread of some time in ms Thread.Sleep(500); counter++; } Console.WriteLine("Thread Ended"); BankAccount account = new BankAccount(10); Thread[] threads = new Thread[15]; Thread.CurrentThread.Name = "main"; for (int k = 0; k < threads.Length; k++) { Thread smolThread = new Thread(account.IssueWidthDraw); smolThread.Name = k.ToString(); threads[k] = smolThread; } foreach (var smolThread in threads) { Console.WriteLine("Thread {0} Alive: {1}", smolThread.Name, smolThread.IsAlive); smolThread.Start(); Console.WriteLine("Thread {0} Alive: {1}", smolThread.Name, smolThread.IsAlive); } Console.WriteLine("Current Priority: " + Thread.CurrentThread.Priority); Console.WriteLine($"Thread {Thread.CurrentThread.Name} Ending"); // Passing data to threads through lambda expressions new Thread(() => { countTo(5); countTo(8); }).Start(); #endregion Console.WriteLine("-------------------------------------------------------"); #region Serialization Animal dummyDum = new Animal(45, 25, "Roar", "Dum"); Stream dummyStream = File.Open("AnimalData.dat", FileMode.Create); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(dummyStream, dummyDum); dummyStream.Close(); dummyDum = null; dummyStream = File.Open("AnimalData.dat", FileMode.Open); binaryFormatter = new BinaryFormatter(); dummyDum = (Animal)binaryFormatter.Deserialize(dummyStream); dummyStream.Close(); Console.WriteLine("Dummy Dum from binary: " + dummyDum.ToString()); dummyDum.Weight = 33; XmlSerializer xmlSerializer = new XmlSerializer(typeof(Animal)); using (TextWriter tw = new StreamWriter(@"D:\C#Data\dummy-dum.xml")) { xmlSerializer.Serialize(tw, dummyDum); } dummyDum = null; XmlSerializer xmlDeserializer = new XmlSerializer(typeof(Animal)); TextReader txtReader = new StreamReader(@"D:\C#Data\dummy-dum.xml"); object obj = xmlDeserializer.Deserialize(txtReader); dummyDum = (Animal)obj; txtReader.Close(); Console.WriteLine("Dummy Dum from XML: " + dummyDum.ToString()); #endregion }