Пример #1
0
        public void CSharpCoding()
        {
            Console.WriteLine("Starting method: CSharp3()");

            var listIntegers = new List <int>();

            listIntegers.AddRange(new int[] { 20, 1, 4, 8, 9, 44, 5, 11, 66, 222, 300, 440, 500, 511 });

            // Find all even numbers in a list of numbers
            List <int> evenNumbers = listIntegers.FindAll(i => (i % 2) == 0);

            Console.WriteLine("\nEven number results:");

            evenNumbers.ForEach(n => Console.WriteLine($"{n}"));

            var largeEvenNumbers = evenNumbers.Where(en => en > 100);

            Console.WriteLine("\nLarge Even Number results:");

            foreach (var L in largeEvenNumbers)
            {
                Console.WriteLine($"{L}");
            }

            int[] myNums = { 12, 5, 11, 2, 44, 30, 1, 7, 5, 4 };

            IEnumerable <int> Bs2 = myNums.Where(n => n < 5);
            // Or older way
            IEnumerable <int> numbersLessThan5 = myNums.Where <int>(delegate(int n) { return(n < 5); });

            Console.WriteLine("Start test: Numbers Less Than 5");
            foreach (var n in numbersLessThan5)
            {
                Console.WriteLine($"{n}");
            }

            // Older way: Call TryGetNewNum passing in an annonymous delegate as a parameter
            int ret = TryGetNewNum(delegate(int n) { int i = n * n; return(i); });

            // Call TryGetNewNum passing in a Lambda Method as a parameter
            int ret2 = TryGetNewNum(n => n * n);

            // Assigning a method implementation to a variable that is a particular type of function signature
            DelegateMakeNumber AddNumberUsingDelegate = delegate(int n) { n += 5; return(n); };
            DelegateMakeNumber AddNumberUsingLambda   = n => n += 50;

            int delegateAnswer = AddNumberUsingDelegate(23);
            int lambdaAnswer   = AddNumberUsingLambda(23);

            // Two arguments, parentheses are required
            DelegateBiggerThan dbt = (nx, s) => s.Length > nx;
            bool isStringBigger    = dbt(10, "012345678");

            // An annonymous object initialized. It is not based on any declared type.
            var newMonkey = new { Name = "Ted", Age = 98, Color = "blue", BirthDate = new DateTime(2000, 2, 14) };

            // ******************************************************************************
            // Type inference
            var    what   = DateTime.Now;
            var    day    = what.Day;
            var    x      = 5;
            var    whatIs = x < 9 ? 14 : 22.8; // Returns a double either way. Return value is inferred to be a double.
            string isThis = whatIs.GetType().Name;

            // Interface sample isx5
            var preferCats = true;
            // IAnimal pet = preferCats ? (IAnimal)(new Cat()) : (IAnimal)(new Dog());
            IAnimal pet = preferCats ? new Cat() as IAnimal : new Dog() as IAnimal;

            // Tail is a public property of Cat. Cannot access through IAnimal in these two scenarios
            //pet.Tail = String.Empty;
            //if(pet.GetType() == typeof(Cat)) pet.Tail = String.Empty;

            var sounds = new List <string>();

            sounds.AddRange(pet.GetCommunicationMethod());
            sounds.ForEach(s => Console.WriteLine(s));

            // Annonymous type making use of object initializers and type inference.
            var    vehicle     = new { Name = "Car1", HorsePwr = 345, Purchasedate = new DateTime(2011, 03, 03) };
            string vehicleType = vehicle.GetType().Name; // vehType is <>f__AnonymousType2`3

            // SampleX4
            // Prepare sample data
            var nameData = new string[] { "Steve", "Jimmy", "Celine", "Arnold" };

            // Transform onto an enumerable of anonymously typed objects
            var people = nameData.Where(str => str != "Jimmy") // Filter out Jimmy
                         .Select(str => new                    // Project on to anonymous type
            {
                Name          = str,
                LettersInName = str.Length,
                IsLongName    = (str.Length > 5)
            });

            Console.WriteLine("Projection Example");

            // people is an annonymous type
            people.ToArray().ToList().ForEach(s => {
                var output = string.Format($"{s.Name} has {s.LettersInName} letters in their name. " +
                                           $"{(s.IsLongName ? "That's long! " : "That's short")}"
                                           );
                Console.WriteLine("{0}", output);
            });

            //----------------------------------------------------------------------------------------
            var teamMembers = new string[] { "Bob Statham", "Cecil Smith", "Donna Cat", "Shirley Grippon", "Ronald Trip" };

            var teamPeople = teamMembers.Where(tm => string.CompareOrdinal(tm, "Ronald") != 0)
                             .Select(m => new
            {
                FullName   = m,
                NameLength = m.Length,
                FirstName  = m.Substring(0, m.IndexOf(' ')),
                LastName   = m.Substring((m.IndexOf(' ') + 1))
            });

            foreach (var tp in teamPeople)
            {
                Console.WriteLine($"FullName: {tp.FullName}  NameLengh: {tp.NameLength}" +
                                  $"First Name: {tp.FirstName}  LastName: {tp.LastName}");
            }
            //---
            // Reverse a string
            var title    = "The best of times is now upon us";
            var titleRev = new StringBuilder(title.Length);

            try
            {
                for (int i = title.Length - 1; i >= 0; i--)
                {
                    titleRev.Append(title[i]);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }
            finally
            {
                Console.WriteLine("Finally statement ran.");
            }

            Console.WriteLine($"title Reversed: {titleRev}");
            //----------------------------------------------------------------------------------------
            Console.WriteLine();

            // Or Retrieve data from the enumerable
            foreach (var person in people)
            {
                var output = string.Format($"{person.Name} has {person.LettersInName} letters in their name.");
                Console.WriteLine(person.IsLongName ? "That' s long! " : "That's short");
                Console.WriteLine(output);
            }

            var myCat = new Cat()
            {
                Feet = 4, Tail = "one"
            };
            var myPet = new { myCat.Feet, myCat.Tail };

            // Callback Functions Demonstration
            const int startingValue   = 10;
            const int interationCount = 5;

            int callBackResult = IncrementCallback(startingValue, interationCount);

            callBackResult = MultiplyCallback(startingValue, interationCount);
            Console.WriteLine("MultiplyCallback demonstration. Result = {0}", callBackResult);

            // Using an object intitializer and an array initializer. Works only for public properties.
            Person personToInit = null;

            personToInit = new Person {
                LastName = "Robertson", Pets = new Pet[2] {
                    new Pet {
                        Name = "Sam", Age = 4
                    }, new Pet {
                        Name = "Radar", Age = 6
                    }
                }
            };

            LogMessage("Log this message using new C# 5.0 attributes");

            // Some string practice
            string s1     = "MyString";
            string result = !string.IsNullOrEmpty(s1)? s1: "default";

            object box1 = null;
            object box2 = new object();
            object box3 = box1 ?? box2;     // null-coalescing operator
            //object box4 = box1 ??= box2;  // null-coalescing assignment operator is only avaiable in language version 8
            // To use Null-coalescing assignment operator ??=, you’ll need to set up your machine to run .NET Core

            int    valueToBox = 100;
            object valueBoxed = valueToBox;

            if (valueBoxed.GetType() == typeof(int))
            {
                int valueUnboxed = (int)valueBoxed;
            }

            // Conversion
            Console.WriteLine("Attempt to make conversion from string to money");
            decimal money = 50;
            //string uservalue = "10B.2";   // This value will cause a format exception
            string uservalue = "108.2";

            try
            {
                money = Convert.ToDecimal(uservalue);
            }
            catch (FormatException fe)
            {
                Console.WriteLine("Unable to make conversion to money: {0}", fe.Message);
            }

            Console.WriteLine($"money: {money}");

            // Or even better because it prevents an exception from being thrown.
            bool conversionWorked = decimal.TryParse(uservalue, out money);

            // Object Initializer example. Optional call to the constructor
            Pod initPod = new Pod()
            {
                Id = 300, Name = "Sam Pod", Qty = 29, StartDate = DateTime.Now, Price = 3.55M, Size = 4, Values = new List <int>()
            };

            // Path class - the second path is absolute, so the first one will be ignored.
            string path11 = "c:\\DatumSuite\\Config";
            string path12 = "\\ctaylor";

            string resultPath = Path.Combine(path11, path12);

            Console.WriteLine("resultPath is: {0}", resultPath);

            string path1 = "c:\\temp";
            string path2 = "subdir\\file.txt";
            string path3 = "c:\\temp.txt";
            string path4 = "c:^*&)(_=@#'\\^&#2.*(.txt";
            string path5 = "";
            string path6 = null;

            CombinePaths(path1, path2);
            CombinePaths(path1, path3);
            CombinePaths(path3, path2);
            CombinePaths(path4, path2);
            CombinePaths(path5, path2);
            CombinePaths(path6, path2);
            CombinePaths(path11, path12);

            string inputFile = @"C:\DatumSuite\ICMA RC\Dev Test\Job_3d91cb3b-efd1-4175-b675-40606ab7242a\Deflate\Input\DeflateFile.gz";
            // Get the path without the file name
            int lastSlashLocation = inputFile.LastIndexOf(@"\");

            inputFile = inputFile.Remove(lastSlashLocation);

            //-----------------------------
            // enums

            // Declared in class: enum cars{Mustang = 1, Corvette = 2, F150 = 3};
            int    selectedCar = 1;
            string firstCar    = Enum.GetName(typeof(cars), selectedCar);
            string secondCar   = Enum.GetName(typeof(cars), 2);
        }