Example #1
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
        }
Example #2
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}");
            }
        }