Exemplo n.º 1
0
        public static void DisplayCountriesInBatchesInReverseOrder(CsvReader dataSource)
        {
            var countries          = dataSource.ReadAllCountriesToList(',');
            var readyToDisplay     = false;
            var countriesToDisplay = 0;

            do
            {
                Console.Write("How much: ");
                readyToDisplay = int.TryParse(Console.ReadLine(), out countriesToDisplay);
            } while (!readyToDisplay);

            int i;

            for (i = countries.Count - 1; i >= 0; i--)
            {
                if (i <= countries.Count - 1 - countriesToDisplay && ((countries.Count - 1 - i) % countriesToDisplay == 0))
                {
                    Console.Write("Press enter to continue or anything else to quit: ");
                    if (Console.ReadLine() != "")
                    {
                        break;
                    }
                }
                Console.WriteLine($"{i + 1}:\t{PopulationFormatter.FormatPopulation(countries[i].Population).PadLeft(15)}: {countries[i].Name}");
            }
            Console.WriteLine($"\n{i} countries displayed.\n");
        }
Exemplo n.º 2
0
        /// <summary>
        /// Testing out LINQ features
        /// </summary>
        /// <param name="filePath"></param>
        static void TestLinqWithList(string filePath)
        {
            System.Console.WriteLine("Using LINQ");
            var csv       = new CsvReader(filePath);
            var countries = (List <Country>)csv.ReadAllCountries();

            System.Console.WriteLine("--------------First 5 using Take() ----------------");
            foreach (var country in countries.Take(5))
            {
                System.Console.WriteLine($"{PopulationFormatter.FormatPopulation((int)country.Population).PadLeft(15)}: {country.Name}");
            }

            System.Console.WriteLine("-------------- Order elements by Name. using .OrderBy(lambda) ----------------");
            foreach (var country in countries.Take(5).OrderBy(x => x.Name))
            {
                System.Console.WriteLine($"{PopulationFormatter.FormatPopulation((int)country.Population).PadLeft(15)}: {country.Name}");
            }

            System.Console.WriteLine("-------------- Language Integrated Query(LINQ) Query Syntax ----------------");
            // LINQ Query is good for long complex queries

            // both filters are doing the same
            var filteredCountries  = countries.Where(x => !x.Code.Contains("FIN"));
            var filteredCountries2 = from country in countries
                                     where !country.Code.Contains("FIN")
                                     select country;

            foreach (var country in filteredCountries2.Take(5).OrderBy(x => x.Name))
            {
                System.Console.WriteLine($"{PopulationFormatter.FormatPopulation((int)country.Population).PadLeft(15)}: {country.Name}");
            }
        }
        public static void Run()
        {
            string filePath = @".\Resources\Pop by Largest Final.csv";
            CsvReaderWithDictryAndList reader = new CsvReaderWithDictryAndList(filePath);

            Dictionary <string, List <Country> > countries = reader.ReadAllCountries();

            foreach (string region in countries.Keys)
            {
                Console.WriteLine(region);
            }

            Console.Write("Which of the above regions do you want? ");
            string chosenRegion = Console.ReadLine();

            if (countries.ContainsKey(chosenRegion))
            {
                // display 10 highest population countries in the selected region
                foreach (Country country in countries[chosenRegion].Take(10))
                {
                    Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
                }
            }
            else
            {
                Console.WriteLine("That is not a valid region");
            }
        }
Exemplo n.º 4
0
        public static void DisplayNFirstCountries(CsvReader dataSource)
        {
            var listToDisplayA = dataSource.ReadNFirstCountries(10, ',');

            foreach (var country in listToDisplayA)
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
        }
Exemplo n.º 5
0
        public static void CollectionsWithLinq(CsvReader dataSource)
        {
            var countries = dataSource.ReadAllCountriesToList(',');

            foreach (var country in countries.Where(x => x.Population > 10000000 && x.Population < 30000000).Take(10).OrderBy(x => x.Name))
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
        }
Exemplo n.º 6
0
        public static void  DisplayAllCountriesFromList(CsvReader dataSource)
        {
            var listToDisplayB = dataSource.ReadAllCountriesToList(',');

            foreach (var country in listToDisplayB)
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
        }
Exemplo n.º 7
0
        /// <summary> Import data from a source into an array </summary>
        static void ImportDataIntoArray(string filePath)
        {
            CsvReader reader = new CsvReader(filePath);

            Country[] countries = reader.ReadFirstNCountries(10);
            foreach (var country in countries)
            {
                System.Console.WriteLine($"{PopulationFormatter.FormatPopulation((int)country.Population).PadLeft(15)}: {country.Name}");
            }
        }
Exemplo n.º 8
0
        static void ImportDataIntoImmutableArrayList(string filePath)
        {
            CsvReader      reader    = new CsvReader(filePath);
            List <Country> countries = (List <Country>)reader.ReadAllCountries();
            var            countriesImmutableBuilder = ImmutableArray.CreateBuilder <Country>();

            countries.ForEach(x => countriesImmutableBuilder.Add(x));
            var countriesImmutable = countriesImmutableBuilder.ToImmutableArray();

            foreach (var country in countriesImmutable)
            {
                System.Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
        }
Exemplo n.º 9
0
        public static void Run()
        {
            string            filePath = @".\Resources\Pop by Largest Final.csv";
            CsvReaderWithList reader   = new CsvReaderWithList(filePath);

            List <Country> countries = reader.ReadAllCountries();

            foreach (Country country in countries.OrderBy(x => x.Name))
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
            //intead of printing all values at once.batching countries up would be nice
            //but, LINQ doesn't support batching. use forloop for batching
            Console.WriteLine("------------------------------------------------------------------");

            // listing the first 20 countries without commas in their names
            var filteredCountries = countries.Where(x => !x.Name.Contains(',')).Take(20);
            //OR
            var filteredCountries2 = from country in countries
                                     where !country.Name.Contains(",")
                                     select country;

            //unlike LINQ method syntax, query syntax don't suppoert all LINQ features(ex: Take(20))
            foreach (Country country in filteredCountries)
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
            //WHERE >it only filters data but it won't remove it physically at an index.LINQ is read-only
            Console.WriteLine();
            Console.WriteLine("------------------------------------------------------------------");

            // listing the 10 highest population countries in alphabetical order.
            // Reverse Where() and Take() to see the impact of swapping chaining order round
            foreach (Country country in countries.Take(10).OrderBy(x => x.Name))
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
            //here think 'countries' as datasorce instead of collection.
            //to LINQ, contries collection is just something that can be enumerated.
            //Most collections implement IEnumerable<T>
            //IEnumerable<T> exposes the ability to supply objects on demand.LINQ methods can leverage that interface.
            //for LINQ, 'countries' is just datasource.it wont care about it is collectio. or not.

            //how it can use orderby without knowing List<T> is a collection?
            //Take is from Enumerable class inside system.Linq Namespace.so, it works with any objects that implement 'IEnumerable<T>'.
            //almost all collections implement IEnumerable<T>, LINQ works for all collections

            //FOR LOOP is for ARRAY & LIST. (not dictionary, as it don't have an index)
            //LINQ works with ARRAY , LIST & DICTIONARY
        }
Exemplo n.º 10
0
        /// <summary>
        /// Import csv into a dictionary
        /// </summary>
        /// <param name="filePath"></param>
        static void ImportDataIntoDictionary(string filePath)
        {
            var csvReader = new CsvReader(filePath);
            var countries = csvReader.ReadAllCountriesDict();

            System.Console.WriteLine("Enter a country code to look up: ");
            string userInput    = Console.ReadLine();
            bool   countryFound = countries.TryGetValue(userInput, out Country country);

            if (!countryFound)
            {
                System.Console.WriteLine($"Country Code {userInput} does not exist in record");
            }
            else
            {
                System.Console.WriteLine($"Found Country: {country.Name} - {PopulationFormatter.FormatPopulation(country.Population)}");
            }
        }
Exemplo n.º 11
0
        public static void DisplayCountriesNDefinedByUser(CsvReader dataSource)
        {
            var countries          = dataSource.ReadAllCountriesToList(',');
            var readyToDisplay     = false;
            var countriesToDisplay = 0;

            do
            {
                Console.Write("How much: ");
                readyToDisplay = int.TryParse(Console.ReadLine(), out countriesToDisplay);
            } while (!readyToDisplay);

            int i;

            for (i = 0; i < Math.Min(countriesToDisplay, countries.Count); i++)
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(countries[i].Population).PadLeft(15)}: {countries[i].Name}");
            }
            Console.WriteLine($"\n{i} countries displayed.\n");
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            string    filepath = @"/home/sheila/Downloads/Countries2015.csv";
            CsvReader reader   = new CsvReader(filepath);
            Dictionary <string, Country> countries = reader.ReadAllCountries();

            Console.WriteLine("Qual código de páis você procura?");
            string userInput = Console.ReadLine();

            bool gotCountry = countries.TryGetValue(userInput, out Country country);

            if (!gotCountry)
            {
                Console.WriteLine($"Desculpe, mas o código {userInput} não foi encontrado.");
            }
            else
            {
                Console.WriteLine($"A população de {country.Name} é de {PopulationFormatter.FormatPopulation(country.Population)}");
            }
        }
Exemplo n.º 13
0
        static void ImportIntoSortedDictionary(string filePath)
        {
            System.Console.WriteLine("-------------Using Sorted Dictionary-------------");

            // sortedli is also a dictionary with key value pairs
            // var sortedli = new SortedList<string, Country>();
            // sortedli.Add("NOR", new Country());

            var csv             = new CsvReader(filePath);
            var countries       = csv.ReadAllCountries();
            var countriesSorted = new SortedDictionary <string, Country>();

            foreach (var country in countries)
            {
                countriesSorted.Add(country.Code, country);
            }
            foreach (var country in countriesSorted.Take(10))
            {
                System.Console.WriteLine($"{PopulationFormatter.FormatPopulation((int)country.Value.Population).PadLeft(15)}: {country.Value.Code}");
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// use lists to import data from the csv and enumerate through
        /// </summary>
        /// <param name="filePath"></param>
        static void ImportDataIntoArrayList(string filePath)
        {
            CsvReader      reader    = new CsvReader(filePath);
            List <Country> countries = (List <Country>)reader.ReadAllCountries();
            var            lilliput  = new Country
            {
                Name       = "Lilliput",
                Code       = "LIL",
                Region     = "Somewhere",
                Population = 2000000
            };
            var index = countries.FindIndex(country => country.Population < 2000000);

            countries.Insert(index, lilliput);
            countries.RemoveAt(index);

            // remove all items in the list where the code is equal to "FIN"
            countries.RemoveAll(x => x.Code.Equals("FIN"));

            foreach (var country in countries)
            {
                System.Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
        }
Exemplo n.º 15
0
        public static void Run()
        {
            Country norway         = new Country("Norway", "NOR", "Europe", 5_282_223);
            Country finland        = new Country("Finland", "FIN", "Europe", 5_511_303);
            Country updatedFinland = new Country("Updated Finland", "FIN", "Europe", 5_511_303);

            var countries = new Dictionary <string, Country>();           //like List, Dictionary also starts its life empty

            countries.Add(norway.Code, norway);
            //countries.Add(norway.Code, norway);//invalid, KEYS should always be unique
            countries.Add(finland.Code, finland);

            //There is no INSERT for dictionary because i	t is not ordered.So, putting a value in particular location is meaningless.

            Console.WriteLine("Enumerating...");
            foreach (var contry in countries)
            {
                Console.WriteLine(contry.Value.Name);
            }
            //or
            foreach (Country nextCountry in countries.Values)
            {
                Console.WriteLine(nextCountry.Name);
            }

            foreach (string key in countries.Keys)
            {
                Console.WriteLine(key);
            }
            Console.WriteLine();

            //Console.WriteLine(countries["MUS"].Name); //error: Keynotfound exception
            bool exists = countries.TryGetValue("MUS", out Country country);

            if (exists)
            {
                Console.WriteLine(country.Name);
            }
            else
            {
                Console.WriteLine("There is no country with the code MUS");
            }


            Console.WriteLine("-------------------------------------------");
            //COLLECTION INITIALIZER for Disctionary
            var countries1 = new Dictionary <string, Country>()
            {
                { norway.Code, norway },
                { finland.Code, finland }
            };            //complier uses Add().Dictionaries always starts its life empty

            countries1.Remove(norway.Code);
            countries1.ContainsKey(norway.Code);

            countries1.Select(i => $"{i.Key}: {i.Value.Name}").ToList().ForEach(Console.WriteLine);
            countries1[finland.Code] = updatedFinland;
            countries1.Select(i => $"{i.Key}: {i.Value.Name}").ToList().ForEach(Console.WriteLine);


            //--------------------------------------------------
            string filePath = @".\Resources\Pop by Largest Final.csv";
            CsvReaderWithDictionary      reader     = new CsvReaderWithDictionary(filePath);
            Dictionary <string, Country> countries2 = reader.ReadAllCountries();

            // NB. Bear in mind when trying this code that string comparison is by default case-sensitive.
            // Hence, for example, to display Finland, you need to type in "FIN" in capitals. "fin" won't work.
            Console.WriteLine("Which country code do you want to look up? ");
            string userInput = Console.ReadLine();

            bool gotCountry = countries2.TryGetValue(userInput, out Country country1);

            if (!gotCountry)
            {
                Console.WriteLine($"Sorry, there is no country with code, {userInput}");
            }
            else
            {
                Console.WriteLine($"{country1.Name} has population {PopulationFormatter.FormatPopulation(country1.Population)}");
            }
        }
Exemplo n.º 16
0
        public static void Run()
        {
            //ARRAY
            string[] daysOfWeek =
            {
                "Monday",
                "Tuesday",
                "Wenesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            };
            //{ }  >collection initializer

            //print all days in order
            //arrays are ordered
            Console.WriteLine("Before:");
            foreach (string day in daysOfWeek)
            {
                Console.WriteLine(day);
            }

            //Replacing Array Items
            daysOfWeek[2] = "Wednesday";

            Console.WriteLine("\r\nBefore:");
            foreach (string day in daysOfWeek)
            {
                Console.WriteLine(day);
            }


            //Array of int
            int[] ints = { 1, 2, 3, 4 };
            //Array of points
            System.Drawing.Point[] points = { new System.Drawing.Point(3, 5) };

            //LOOK OF AN ITEM IN ARRAY
            Console.WriteLine("Which day do you want to display?");
            Console.Write("(Monday = 1, etc.) > ");
            int iDay = int.Parse(Console.ReadLine());

            string chosenDay = daysOfWeek[iDay - 1];

            Console.WriteLine($"That day is {chosenDay}");

            //-------------------
            //READ DATA FROM EXTERNAL DATA SOURCE INTO AN ARRAY
            //dynamically put data in array
            //Arrays are Uniquitous (constantly encountered)
            //uninitialized array contains nulls (for reference types)
            //Arrays are normal reference types.(there can be null)
            //Arrays always start with full null/default values.(value is null(ref type) if not initialialized)
            string             filePath = @".\Resources\Pop by Largest Final.csv";
            CsvReaderWithArray reader   = new CsvReaderWithArray(filePath);

            Country[] countries = reader.ReadFirstNCountries(10);

            foreach (Country country in countries)
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }


            //------------------------
            Country[] countries1 = null; //this is just declaration , not instantiation
            //int number = null;//invalid since it is value type
            int[] numbers = null;        //valid since arrays are reference types

            //arrays are fixed size, so array cannot be created with specifying size.
            Country[] countries2 = new Country[10]; //array with all nulls

            int[] ints1 = new int[10];              //array with all 0's (int default value =0)

            int[] ints2 = new int[] { 1, 2, 3, 4 }; //array initializer
            //or
            int[] ints3 = { 1, 2, 3, 4 };
        }
Exemplo n.º 17
0
        public static void Run()
        {
            List <int> ints = new List <int>();          //List<T> always starts with empty.it don't have a special constructor.
            //int[] ints = new int[10];//Arrays instantiated with special sytax [], as it part of .net Runtime
            //Lists are not part of .Net Runtime.so,normal syntax for new objects
            List <string> daysOfWeek = new List <string>
            {
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            };            //unlike array,here Under the hood the compilar turns collection initalizer{} to .Add("day") method like below.

            List <string> daysOfWeek1 = new List <string>();

            daysOfWeek1.Add("Monday");
            daysOfWeek1.Add("Tuesday");
            daysOfWeek1.Add("Wednesday");
            daysOfWeek1.Add("Thursday");

            //---------------List<T> ---------
            //T is a generic type.Generic type applies to all the collections in C# except Arrays.
            //Arrays can't be generic.
            //T[] generic=new T[10];//invalid


            //--------------------------
            string            filePath = @".\Resources\Pop by Largest Final.csv";
            CsvReaderWithList reader   = new CsvReaderWithList(filePath);

            List <Country> countries = reader.ReadAllCountries();

            // This is the code that inserts and then subsequently removes Lilliput.
            // Comment out the RemoveAt to see the list with Lilliput in it.
            Country lilliput      = new Country("Lilliput", "LIL", "Somewhere", 2_000_000);
            int     lilliputIndex = countries.FindIndex(x => x.Population < 2_000_000);

            countries.Insert(lilliputIndex, lilliput);
            Console.WriteLine("-----------" + lilliputIndex + "---" + lilliput.Name + "------------");
            countries.RemoveAt(lilliputIndex);
            //INSERT * REMOVE from list casuses to shift all the data after index which reduces performance.careful

            foreach (Country country in countries)
            {
                Console.WriteLine($"{PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
            Console.WriteLine($"{countries.Count} countries");

            //finding item by code
            int     index           = countries.FindIndex(x => x.Code == "USA");
            Country selectedCountry = countries[index];

            Console.WriteLine("---------SelectedCountry: " + JsonConvert.SerializeObject(selectedCountry));
            //OR
            //USE DICTIONARY //prefer



            //---------------MANIPULATING LIST DATA-------------------------
            //foreach is simple but it has no control.
            //for loop give finer control for LISTS AND ARRAYS.difficult for DICTIONARIES.


            string            filePath1 = @".\Resources\Pop by Largest Final.csv";
            CsvReaderWithList reader1   = new CsvReaderWithList(filePath1);

            List <Country> countries1 = reader.ReadAllCountries();

            // comment this out to see all countries, without removing the ones with commas
            reader1.RemoveCommaCountries(countries1);

            Console.Write("Enter no. of countries to display> ");
            bool inputIsInt = int.TryParse(Console.ReadLine(), out int userInput);

            if (!inputIsInt || userInput <= 0)
            {
                Console.WriteLine("You must type in a +ve integer. Exiting");
                return;
            }

            //int maxToDisplay = Math.Min(userInput, countries.Count);
            int maxToDisplay = userInput;

            //display from start
            for (int i = 0; i < countries.Count; i++)
            {
                if (i > 0 && (i % maxToDisplay == 0))
                {
                    Console.WriteLine("Hit return to continue, anything else to quit>");
                    if (Console.ReadLine() != "")
                    {
                        break;
                    }
                }

                Country country = countries[i];
                Console.WriteLine($"{i + 1}: {PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }

            //display from end
            for (int i = countries.Count - 1; i >= 0; i--)
            {
                int displayIndex = countries.Count - 1 - i;
                if (displayIndex > 0 && (displayIndex % maxToDisplay == 0))
                {
                    Console.WriteLine("Hit return to continue, anything else to quit>");
                    if (Console.ReadLine() != "")
                    {
                        break;
                    }
                }

                Country country = countries[i];
                Console.WriteLine($"{displayIndex + 1}: {PopulationFormatter.FormatPopulation(country.Population).PadLeft(15)}: {country.Name}");
            }
        }