static void Main(string[] args)
        {
            //ArrayList


            ArrayList al = new ArrayList();
            int       a  = 101;

            al.Add(a);
            al.Add("This is a arraylist");
            al.Add(2.3f);
            al.Insert(3, "This is the forth index");

            ArrayList al2 = new ArrayList();

            al2.Add(102);
            al.InsertRange(1, al2);
            Console.WriteLine("ArrayList:");
            Console.WriteLine();
            foreach (var ele in al)
            {
                Console.WriteLine(ele + " ");
            }
            Console.WriteLine("The count of the arraylist is {0}", al.Count);
            Console.WriteLine("The capacity of the arraylist is {0}", al.Capacity);
            Console.WriteLine();
            // Hash table

            Hashtable ht = new Hashtable();

            ht.Add(1, "one");
            ht.Add(2, "two");
            ht.Add(0.3f, 2);
            ht.Add(4, null);
            ht.Add("Hema", "vathi");
            ht.Remove(2);
            // ht.Clear();
            Console.WriteLine("Hashtable:");
            Console.WriteLine();
            foreach (DictionaryEntry ele in ht)   //ht.keys means only print a key values for values the viceversa is applied.
            {
                Console.WriteLine("{0},{1}", ele.Key, ele.Value);
            }
            String firstelement = (string)ht[1];
            String str          = (string)ht["Hema"];

            Console.WriteLine("The first element in the hashtable is {0}", firstelement);
            Console.WriteLine("The last element in the hashtable is {0}", str);
            Console.WriteLine("The hash table contains a 0.3  is {0}", ht.Contains(0.3f));
            Console.WriteLine();

            //SortedList
            Console.WriteLine("Sorted List:");
            SortedList sl = new SortedList();

            sl.Add(2, "two");
            sl.Add(1, "one");
            sl.Add(0, "zero");
            sl.RemoveAt(0);
            foreach (DictionaryEntry i in sl)
            {
                Console.WriteLine("{0},{1}", i.Key, i.Value);
            }
            Console.WriteLine();

            //stack

            Console.WriteLine("Stack:");
            Stack s = new Stack();

            s.Push("hello");
            s.Push(102);
            s.Push(102);
            s.Push(.3f);
            foreach (var item in s)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("The first element will be deleted is {0} ", s.Peek());
            Console.WriteLine();

            //Queue

            Console.WriteLine("Queue:");
            Queue q = new Queue();

            q.Enqueue(34);
            q.Enqueue("thirtyfour");
            q.Enqueue(3.4);
            q.Dequeue();
            foreach (var item in q)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("The first element of the queue is {0}", q.Peek());
        }
예제 #2
0
        static void Main(string[] args)
        {
            //ArrayLists
            ArrayList numbers = new ArrayList();

            numbers.Add(5);
            numbers.Insert(0, 9); //inserts a value at the index marked
            numbers.Remove(5);    //removes first instance of the value
            numbers.RemoveAt(0);  //removes the index supplied

            //Can add all data types within arraylists even if it causes errors
            //numbers.Add("Hello");
            foreach (int i in numbers)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine($"There are currently {numbers.Count} elements in the arraylist.");


            //create array list
            //add 5-10 numbers
            //create a result variable
            //use a foreach loop to add them all together into the result variable
            //display the result in the console
            ArrayList values = new ArrayList();

            values.Add(1);
            values.Add(2);
            values.Add(3);
            values.Add(4);
            values.Add(5);
            int result = 0;

            foreach (int i in values)
            {
                result += i;
            }
            Console.WriteLine($"The values added together is {result}");

            Console.WriteLine();
            //Hashtables
            Hashtable ht = new Hashtable();

            ht.Add("001", "John");
            ht.Add("002", "Paul");
            //Can add all datatypes even if it causes an error
            //ht.Add(2, true);
            Console.WriteLine(ht["001"]);

            Console.WriteLine();
            //Lists

            //blank list
            //List<int> numList = new List<int>();

            //adding multiple objects when creating a list
            List <int> numList = new List <int>
            {
                1,
                2,
                3,
                4
            };

            numList.Add(5);
            numList.Insert(0, 9);
            //numList.Remove(5);
            //numList.RemoveAt(0);
            foreach (int i in numList)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine($"There are {numList.Count} elements in the List");
            numList[0] = 1;//can access any index like you would with an array
            int numResult = numList[0];

            Console.WriteLine();
            //Dictionary
            Dictionary <string, bool> tasty = new Dictionary <string, bool>();

            tasty.Add("Chicken Curry", true);
            tasty.Add("Asparagus", false);

            Console.WriteLine(tasty["Chicken Curry"]);
            Console.WriteLine(tasty["Asparagus"]);

            //How to use user input to get value
            Console.WriteLine("Which food would you like to check?");
            string input       = Console.ReadLine();
            bool   resultTasty = tasty[input];

            Console.WriteLine(resultTasty);

            bool foodTest;

            if (tasty.TryGetValue("Doritos", out foodTest))
            {
                Console.WriteLine($"Could find key. Here is value: {foodTest} ");
            }
            else
            {
                Console.WriteLine("Could not find key");
            }

            //how to loop through dictionary
            foreach (KeyValuePair <string, bool> kvp in tasty)
            {
                //How to access key and value in foreach
                //Console.WriteLine(kvp.Key);
                //Console.WriteLine(kvp.Value);

                if (kvp.Value == true)
                {
                    Console.WriteLine($"{kvp.Key} is tasty!");
                }
                else
                {
                    Console.WriteLine($"{kvp.Key} is icky!");
                }
            }
        }
예제 #3
0
        static void Main(string[] args)
        {
            // Array List //

            ArrayList list = new ArrayList();

            Course c1 = new Course();
            Course c2 = new Course();
            Course c3 = new Course();

            list.Add(c1);
            list.Insert(1, c2);

            int i = list.IndexOf(c1);
            //     Console.WriteLine("Index of c1 is :"+i);

            int j = list.IndexOf(c2);
            //    Console.WriteLine("Index of c2 is :" + j);

            bool a = list.Contains(c1);
            //   Console.WriteLine("c1 is contain in this list "+a);

            bool b = list.Contains(c3);
            //    Console.WriteLine("c3 is contain in this list "+b);


            //Hashtable//

            Hashtable ages = new Hashtable();

            ages["Sabbir"] = 28;
            ages["Rahim"]  = 21;
            ages["Karim"]  = 25;

            // Console.WriteLine("Age of Sabbir " + ages["Sabbir"]);

            // we can't use for loop in Hashtable. We need Foeratch loop


            /*      foreach (DictionaryEntry age in ages)
             *    {
             *        Console.WriteLine(age.Value);
             *    }
             *
             *    foreach (DictionaryEntry age in ages)
             *    {
             *        Console.WriteLine(age.Key);
             *    }
             */
            foreach (DictionaryEntry age in ages)
            {
                string c = (string)age.Key;
                int    d = (int)age.Value;
                Console.WriteLine("{0} => {1}", c, d);
            }

            // Boxing

            int k = 10;

            object box = k;

            Console.WriteLine(k.GetType());

            Course c5 = new Course();

            box = c5;
            Console.WriteLine(c5.GetType());

            // UnBoxing

            c5 = (Course)box;

            // Sorted List [ print sequenly]

            SortedList s1 = new SortedList();

            s1["en-us"] = "United stste";
            s1["en-uk"] = "United kingdom";
            s1["bn"]    = "Bangla";
            s1["in"]    = "India";
            s1["ar"]    = "Arabic";

            foreach (DictionaryEntry s in s1)
            {
                string e = (string)s.Key;
                string f = (string)s.Value;
                Console.WriteLine("{0} => {1}", e, f);
            }
        }
예제 #4
0
        static void Main(string[] args)
        {
            int    a = 10;
            string b = "Hello";
            float  c = 2.32f;
            char   d = 'd';
            bool   e = true;

            int[] f = new int[6] {
                1, 2, 3, 4, 5, 6
            };
            ArrayList Array1 = new ArrayList();
            ArrayList Array2 = new ArrayList()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            };

            Array1.Add(a);
            Array1.Add(b);
            Array1.Add(c);
            Array1.Add(d);
            Array1.Add(e);
            Array1.Add(f);
            Array1.Add("bcd");

            var dcd = Array1[6];     //Just for the sake of explicit typecasting

            Array1.Insert(0, a * 2); //inserting value a*2 at 0 index
            //by inserting every value will be pushed forward to the next location.

            Array1.AddRange(Array2);//adding another array list at the end of the first array list

            for (int i = 0; i < Array1.Count; i++)
            {
                Console.WriteLine("Value from {0} index ", i);
                Console.WriteLine(Array1[i]);
            }
            Console.WriteLine("\n Ended The array List Now moving towards next Collection \n\n\n");


            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            //Code for Sorted List (Non generic)
            Console.WriteLine("From Sorted List Nongeneric");
            int        j       = 0;
            SortedList myNames = new SortedList();

            myNames.Add(j, a);
            j++;
            myNames.Add(j, b);
            j++;
            myNames.Add(j, c);
            j++;
            myNames.Add(j, d);
            j++;
            myNames.Add(j, e);
            j++;
            myNames.Add(j, f);
            j++;

            Console.WriteLine("Before removing an element");
            foreach (DictionaryEntry variable in myNames)
            {
                Console.WriteLine("{0} {1}", variable.Key, variable.Value);
            }

            myNames.RemoveAt(0);
            Console.WriteLine("After removing an element");
            foreach (DictionaryEntry variable in myNames)
            {
                Console.WriteLine("{0} {1}", variable.Key, variable.Value);
            }



            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Code for Sorted List (Generic)
            Console.WriteLine("\n\n\n From Sorted List Generic");
            j = 0;
            SortedList <int, string> myNames1 = new SortedList <int, string>();

            myNames1.Add(j, "a");
            j++;
            myNames1.Add(j, "b");
            j++;
            myNames1.Add(j, "c");
            j++;
            myNames1.Add(j, "d");
            j++;
            myNames1.Add(j, "e");
            j++;
            myNames1.Add(j, "f");
            j++;

            myNames1.Remove(1);
            foreach (var variable in myNames1)
            {
                Console.WriteLine("The value against key {0} is {1}", variable.Key, variable.Value);
            }

            Console.WriteLine("\n\n\n Using KeyValuePair Property");

            foreach (KeyValuePair <int, string> obj in myNames1)
            {
                Console.WriteLine("{0} {1}", obj.Key, obj.Value);
            }
            string result;

            if (myNames1.TryGetValue(2, out result))
            {
                Console.WriteLine("true {0}", result);
            }
            //Console.WriteLine(myNames1[0]);



            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Code for Dictionary implementation starts here
            Console.WriteLine("\n\n\n From Dictionary");

            Dictionary <char, string> dict = new Dictionary <char, string>();

            dict.Add('a', "Ali");
            dict.Add('b', "Batman");
            dict.Add('c', "Cat");
            dict.Add('d', "Dog");
            dict.Add('e', "Elephant");
            dict.Add('f', "Frog");
            foreach (Object obj in dict)
            {
                Console.WriteLine(obj);
            }

            dict.Add('g', "Goose");
            dict.Remove('a');

            Console.WriteLine("\n\n From Dictionary Generic Printing Count of objects");
            Console.WriteLine(dict.Count);

            Console.WriteLine("\n\n\n From Dictionary Generic using Object");
            foreach (Object obj in dict)
            {
                Console.WriteLine(obj);
            }
            Console.WriteLine("\n\n\n From Dictionary Generic using KeyValuePair");
            foreach (KeyValuePair <char, string> obj in dict)
            {
                Console.WriteLine("{0} {1}", obj.Key, obj.Value);
            }



            //Code for HashTable implementation starts here
            Console.WriteLine("\n\n\n From Hashtable");

            Hashtable hash = new Hashtable();

            hash.Add(1, a);
            hash.Add('a', b);
            hash.Add('b', b);
            hash.Add('d', b);
            foreach (DictionaryEntry obj in hash)
            {
                Console.WriteLine("{0} {1}", obj.Key, obj.Value);
            }
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            //Code for List implementation starts here
            Console.WriteLine("\n\n\n From List generic");

            List <int> myList = new List <int>();

            myList.Add(1);
            myList.Add(21);
            myList.Add(2);
            myList.Add(0);
            myList.Sort();
            for (int i = 0; i < myList.Count; i++)
            {
                Console.WriteLine(myList[i]);
            }
            myList.RemoveAt(0);
            myList.Insert(0, 20);
            myList.Sort();
            for (int i = 0; i < myList.Count; i++)
            {
                Console.WriteLine(myList[i]);
            }


            List <ArrayList> myCollector = new List <ArrayList>();

            myCollector.Add(Array1);
            myCollector.Add(Array2);
            Console.WriteLine("\n\n" + myCollector[0].ToArray().Length);


            //Adding dummy student data into the list of students


            int                age;
            float              cgpa;
            string             name;
            string             email;
            string             address;
            string             contactNumber;
            List <StudentInfo> myClass = new List <StudentInfo>();
            StudentInfo        bacs    = new StudentInfo();

            myClass.Add(bacs);
            myClass.Add(bacs);
            for (int i = 0; i < 0; i++)
            {
                Console.WriteLine("Write the age of {0} student", i + 1);
                age = int.Parse(Console.ReadLine());
                Console.WriteLine("Write the cgpa of {0} student", i + 1);
                cgpa = float.Parse(Console.ReadLine());
                Console.WriteLine("Write the name of {0} student", i + 1);
                name = Console.ReadLine();
                Console.WriteLine("Write the email of {0} student", i + 1);
                email = Console.ReadLine();
                Console.WriteLine("Write the address of {0} student", i + 1);
                address = Console.ReadLine();
                Console.WriteLine("Write the contactNumber of {0} student", i + 1);
                contactNumber = Console.ReadLine();

                myClass.Add(new StudentInfo(age, cgpa, name, email, address, contactNumber));
            }
            foreach (StudentInfo s in myClass)
            {
                if (s.AGE >= 18)
                {
                    Console.WriteLine("The student details are as follow");
                    Console.WriteLine("The Name of the student is {0}", s.NAME);
                    Console.WriteLine("The Age of the student is {0}", s.AGE);
                    Console.WriteLine("The Cgpa of the student is {0}", s.CGPA);
                    Console.WriteLine("The Email of the student is {0}", s.EMAIL);
                    Console.WriteLine("The Address of the student is {0}", s.ADDRESS);
                    Console.WriteLine("The Contact Number of the student is {0}", s.CONTACTNUMBER);
                }
            }
            var results = from StudentInfo in myClass
                          where StudentInfo.AGE >= 12
                          select StudentInfo;

            Console.WriteLine("Student with age greater then 12 are as follow");

            foreach (StudentInfo s in results)
            {
                Console.WriteLine(s.AGE);
            }

            /*
             * myClass.Select(x=>new object { name=x.Total})
             *
             * var results = from s in myClass
             *            select s;
             *
             * foreach(StudentInfo info in myClass)
             *  {
             * Console.WriteLine(results[0]);*/


            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            ///


            //Code for Stack implementation starts here
            Console.WriteLine("\n\n\n Implementation of Stack starts from here \n");
            Stack <int> myStack = new Stack <int>(f);


            Console.WriteLine("\nStack after entering values using array \n");
            foreach (int variable in myStack)
            {
                Console.Write(variable + ",");
            }
            Console.WriteLine();


            Console.WriteLine("\nStack after entering Value using push \n");
            myStack.Push(20);
            foreach (int variable in myStack)
            {
                Console.Write(variable + ",");
            }


            Console.WriteLine("\nStack after Peeking from it \n");
            Console.WriteLine(myStack.Peek());
            foreach (int variable in myStack)
            {
                Console.Write(variable + ",");
            }


            Console.WriteLine("\nStack after popping element from it \n");
            Console.WriteLine(myStack.Pop());
            foreach (int variable in myStack)
            {
                Console.Write(variable + ",");
            }
            Console.WriteLine();
            int check = 24;

            if (myStack.Contains(check))
            {
                Console.WriteLine("true the stack contains the value {0}", check);
            }
            else
            {
                Console.WriteLine("False the stack doesnot contains the value {0}", check);
            }


            //Iplementation of queue starts from here
            Queue <int> myQueue = new Queue <int>(f);

            Console.WriteLine("\nQueue after entering values from array");
            foreach (int variable in myQueue)
            {
                Console.Write(variable + ",");
            }

            myQueue.Enqueue(20);
            Console.WriteLine("\n\nQueue after using enqueue");
            foreach (int variable in myQueue)
            {
                Console.Write(variable + ",");
            }



            Console.WriteLine("\n\nQueue after Dequeue method");
            Console.WriteLine("The value returned from the dequeue method is " + myQueue.Dequeue());
            foreach (int variable in myQueue)
            {
                Console.Write(variable + ",");
            }


            Console.WriteLine("\n\nPrinting the count of elements in the queue \n" + myQueue.Count());

            Console.WriteLine("\nQueue after Peeking from it");
            Console.WriteLine("Value returned from peek method is " + myQueue.Peek());
            foreach (int variable in myQueue)
            {
                Console.Write(variable + ",");
            }

            Console.WriteLine();

            ///////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////
            ///////////////////////////////////////////////////////////////
            //File Hanlding
            string path1 = @"C:\Users\Lenovo\source\repos\Collections\Collections\bin\Debug\netcoreapp3.1/DummyData1.txt";
            string path2 = @"C:\Users\Lenovo\source\repos\Collections\Collections\bin\Debug\netcoreapp3.1/DummyData2.txt";
            string path3 = @"C:\Users\Lenovo\source\repos\Collections\Collections\bin\Debug\netcoreapp3.1/DummyData3.txt";

            string Abc  = "Hello from the file1";
            string Abcd = "Hello from the file2";

            /*File.WriteAllText(path1,Abc);
             * File.WriteAllText(path2, Abcd);
             */
            string DataRead = File.ReadAllText(path1);

            Console.WriteLine(DataRead);

            //This block is used to to auto close the file after the use
            //the file will open at the start of the using block and
            //At the end of the block the file is automatically closed.

            /*using (StreamWriter sw = File.AppendText(path1))
             * {
             *  sw.WriteLine("\nHello once again using Stream Writer");
             * }
             *
             * using (StreamReader sr = File.OpenText(path2))
             * {
             *  string readed = "";
             *  while ((readed = sr.ReadLine()) != null)
             *  {
             *      Console.WriteLine(readed);
             *  }
             * } */

            DataRead = File.ReadAllText(path1);
            Console.WriteLine("\n\n" + DataRead + "\n\n");

            DataRead = File.ReadAllText(path2);
            Console.WriteLine("\n\n" + DataRead + "\n\n");


            /*FileStream file = new FileStream(path3, FileMode.OpenOrCreate , FileAccess.ReadWrite);
             * //file.Write("Hello")
             * file.WriteByte(66);
             * file.Close();
             */
            using (FileStream file1 = new FileStream(path3, FileMode.Append, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(file1, Encoding.UTF8))
                {
                    int[] arrays = new int[10] {
                        1, 2, 3, 4, 5, 6, 7, 8, 9, 10
                    };
                    foreach (int num in arrays)
                    {
                        sw.Write(num + " ");
                    }

                    sw.WriteLine("\nHelpppp");
                }
            }


            using (FileStream file1 = new FileStream(path3, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(file1))
                {
                    string line = sr.ReadLine();
                    while (line != null)
                    {
                        Console.WriteLine(line);
                        line = sr.ReadLine();
                    }
                }
            }



            //Exception Handling Code
            int[] except = new int[3] {
                1, 2, 3
            };
            try
            {
                Console.WriteLine(except[10]);
            }
            catch (Exception error)
            {
                Console.WriteLine(error.Message);
            }
            finally
            {
                Console.WriteLine("The try catch Block has ended");
            }

            /*using (FileStream fs = new FileStream(path1, FileMode.Open, FileAccess.Read))
             * {
             *  using(StreamWriter stw = new StreamWriter(fs))
             *  {
             *
             *  }
             *
             *  using(StreamReader str = new StreamReader(fs))
             *  {
             *
             *  }
             *
             * }*/



            //Manipulating the tuples in the form of an array
            Tuple <int, float, double, char, string>[] studentTuples = new Tuple <int, float, double, char, string> [2];

/*            Tuple<int, float, double, char, string>[] studentFiltered = new Tuple< int, float, double, char, string>[2];
 */
            for (int i = 0; i < 2; i++)
            {
                studentTuples[i] = new Tuple <int, float, double, char, string>(1, 2.2f, 3.3, 'a', "abcd");
            }

            /*int iterator=0;*/
            foreach (Tuple <int, float, double, char, string> tp in studentTuples)
            {
                /*if (tp.Item5.Length >= 3)
                 * {
                 *  studentFiltered[iterator] = tp;
                 *  iterator++;
                 * }*/
                Console.Write(tp.Item1 + " , ");
                Console.Write(tp.Item2 + " , ");
                Console.Write(tp.Item3 + " , ");
                Console.Write(tp.Item4 + " , ");
                Console.WriteLine(tp.Item5);
            }
            //var v1 = new Tuple.Create(1,2);



            //Manilulating with the string array using LINQ queries
            string[] myNamesArray = new string[22] {
                "Ali", "Yar", "Wamik", "Afaq", "Salal", "Daniel", "June", "Juliet",
                "danyyal", "Yousuf", "Bukht", "Yar", "Arshad", "Kainat", "aiman", "sidra",
                "Tooba", "zeeshan", "Hyper", "Don", "Chaudary", "Muaaz"
            };
            var MyQueryResult = from names in myNamesArray
                                where names.Length >= 3
                                select names;

            Console.WriteLine("name---first2letters--Caps--length");
            foreach (var names in MyQueryResult)
            {
                Console.Write(names + " ");
                Console.Write(names.Substring(0, 2) + " ");
                Console.Write(names.ToUpper() + " ");
                Console.WriteLine(names.ToUpper().Length);
            }



            //Maipulatin with Tuple array using the LINQ queries
            var myTupleResults = studentTuples.Where(tuples => tuples.Item5.Substring(0, 2) == "ab" && tuples.Item5.Contains('b') && tuples.Item1 == 1);


            //We can write queries in Two ways

            /*from tuples in studentTuples
             * where tuples.Item5.Substring(0, 2) == "ab" && tuples.Item5.Contains('b') && tuples.Item1==12
             * select tuples;*/

            //Getting array in the resul of LINQ Queries
            var myTupleResultsArray = studentTuples.Where(tuples => tuples.Item5.Substring(0, 2) == "ab" && tuples.Item5.Contains('b') && tuples.Item1 == 1).ToArray();

            Console.WriteLine(myTupleResultsArray[0]);



            Console.WriteLine("\n\n From Tuples results\nName---first2letters--Caps--length");
            foreach (var tuples in myTupleResults)
            {
                Console.Write(tuples.Item1 + " ");
                Console.Write(tuples.Item2 + " ");
                Console.Write(tuples.Item3 + " ");
                Console.Write(tuples.Item4.ToString() + " ");
                Console.WriteLine(tuples.Item5.Substring(0));
            }
            Program pg = new Program();

            MakeNoise mk = new MakeNoise(pg.Noise);

            mk(10);
        }