Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            MyList<string> test = new MyList<string>(7);
            test.Add("lol0");
            test.Add("lol2");
            test.Add("lol1");
            Console.WriteLine("lol0 "+test.GetElementByIndex(0));
            Console.WriteLine("lol2 " + test.GetElementByIndex(1));
            Console.WriteLine("lol1 " + test.GetElementByIndex(2));
            Console.WriteLine("lol1 " + test.GetLastElement());
            test.RemoveLastElement();
            Console.WriteLine("lol2 " + test.GetLastElement());
            Console.WriteLine("2 "+test.getCount());
            test.RemoveFirstElement();
            Console.WriteLine("lol2 "+test.GetLastElement());
            Console.WriteLine("1 "+test.getCount());
            test.InsertElementAt(0, "lol2");
            Console.WriteLine("lol2 " + test.GetLastElement());
            test.InsertElementAt(1, "lol3");
            test.InsertElementAt(1, "lol4");
            Console.WriteLine("4 " +test.getCount());
            test.RemoveLastElement();
            Console.WriteLine("lol3 "+test.GetLastElement());
            test.RemoveLastElement();
            Console.WriteLine("lol4 " + test.GetLastElement());

            foreach (var item in test)
            {
                Console.WriteLine(item);
            }

            Console.Read();
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            MyList<int> mylist = new MyList<int>();
            mylist.Add(213);
            mylist.Add(13);
            mylist.Add(1);
            mylist.Add(23);
            mylist.Insert(1,2);
            mylist.RemoveAt(4);
            mylist[0] = 100;
            for (int i = 0; i < mylist.Count; i++)
            {
                //Console.WriteLine(mylist.GetItem(i));
                Console.WriteLine(mylist[i]);
            }
            Console.WriteLine(mylist.IndexOf(13));
            Console.WriteLine(mylist.LastIndexOf(2));
            mylist.Sort();
            for (int i = 0; i < mylist.Count; i++)
            {
                //Console.WriteLine(mylist.GetItem(i));
                Console.WriteLine(mylist[i]);
            }

            Console.ReadKey();
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            MyList<int> generic_int = new MyList<int>();
            generic_int.Add(-1);
            generic_int.Add(2);
            generic_int.Add(3);

            MyList<float> genfloat = new MyList<float>();
            genfloat.Add(2.45f);
            genfloat.Add(2.46f);
            genfloat.Add(2.47f);
            genfloat.Add(2.48f);
            genfloat.Add(2.49f);
            Console.WriteLine("Друкуемо раз:");
            foreach (var item in generic_int)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("Друкуемо два:");
            foreach (var item in genfloat)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine(generic_int.IndexOf(2));
            generic_int.Remove(2);
            Console.WriteLine(generic_int.IndexOf(2));
            Console.WriteLine("Писля удаления:");
            foreach (var item in generic_int)
            {
                Console.WriteLine(item);
            }

        }
Ejemplo n.º 4
0
        public MyList<Position> GetCastling()
        {
            MyList<Position> castling = new MyList<Position>();
            Figure fig;
            int x = Position.GetX();
            if (ismoved())
                return castling;
            Side oppside = GetEnemySide();
            int ypos = (this.Side == Side.White) ? 1 : 8;
            if (chessfield.isDangerPosition(oppside, Position))
                return castling;

            fig = chessfield.GetFigureAt(new Position(1, ypos));
            if (fig != null &&
                !chessfield.isDangerPosition(oppside, new Position(x-1,ypos))    &&
                !chessfield.isDangerPosition(oppside, new Position(x - 2, ypos)) &&
                !chessfield.isDangerPosition(oppside, new Position(x - 3, ypos)) &&
                !chessfield.isDangerPosition(oppside, new Position(x, ypos)) &&
                !fig.ismoved() &&
                chessfield.GetFigureAt(new Position(2, ypos)) == null &&
                chessfield.GetFigureAt(new Position(3, ypos)) == null &&
                chessfield.GetFigureAt(new Position(4, ypos)) == null)
                                castling.Add(fig.Position);

             fig = chessfield.GetFigureAt(new Position(8, ypos));
             if (fig != null &&
                 !chessfield.isDangerPosition(oppside, new Position(x + 1, ypos)) &&
                 !chessfield.isDangerPosition(oppside, new Position(x + 2, ypos)) &&
                 !chessfield.isDangerPosition(oppside, new Position(x, ypos)) &&
                 !fig.ismoved() &&
                 chessfield.GetFigureAt(new Position(7, ypos)) == null &&
                 chessfield.GetFigureAt(new Position(6, ypos)) == null)
                    castling.Add(fig.Position);
            return castling;
        }
 public static void TestClear(MyList<int> Inlist)
 {
     Inlist.Add(1);
     Inlist.Add(2);
     Inlist.Add(3);
     Inlist.Clear();
     Debug.Assert(Inlist.numItems == 0);
 }
 public static void TestAdd(MyList<int> Inlist)
 {
     Inlist.Add(3);
     Debug.Assert(Inlist[0] == 3);
     Inlist.Add(4);
     Debug.Assert(Inlist[1] == 4);
     Inlist.Add(-323875);
     Debug.Assert(Inlist[2] == -323875);
 }
Ejemplo n.º 7
0
 static void Main(string[] args)
 {
     MyList<string> stringList = new MyList<string>();
     stringList.Add("Hello");
     stringList.Add("world");
     Console.WriteLine(stringList.Count);
     stringList.Add("Oksana");
     Console.WriteLine(String.Format("{0} {1}", stringList[0], stringList[1]));
     Console.ReadKey();
 }
Ejemplo n.º 8
0
        public void should_Insert_Single_Item_In_MyList_Instance()
        {
            var myList = new MyList();
            myList.Add(1);
            myList.Add(3);
            myList.Insert(1,2);

            Assert.AreEqual(3, myList.Count);
            Assert.AreEqual(3, myList.Capacity);
        }
Ejemplo n.º 9
0
        public void should_Insert_Multiple_Items_In_MyList_Instance()
        {
            var myList = new MyList();
            myList.Add(2);
            myList.Add(4);
            myList.Insert(1,3);
            myList.Insert(0,1);

            Assert.AreEqual(4, myList.Count);
        }
Ejemplo n.º 10
0
        private void A37_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
            {
                return;
            }
            string msg = isPT() ? String.Format("Com que tipo de gasolina o(a) Sr(a). geralmente abastece seu {0}?", rowCurrent["A4_A_NOME"]) : String.Format("¿Con qué tipo de nafta reabastece normalmente su {0}?", rowCurrent["A4_A_NOME"]);
            Label3.Text = msg;

            MyList<string> list = new MyList<string>();
            list.Add(isPT() ? "Petrobras: 101.5 octanas" : "Petrobras: 101.5 octanos");
            list.Add(isPT() ? "YPF fangio XXI: 98 octanas" : "YPF fangio XXI: 98 octanos");
            list.Add(isPT() ? "SHELL V-Power: 97,5 octanas" : "SHELL V-Power: 97.5 octanos");
            list.Add(isPT() ? "SUPER: 93,5 a 95 octanas" : "SUPER: 93.5 a 95 octanos");
            list.Add(isPT() ? "Comum: 83 a 85 octanas" : "Común: 83 a85 octanos");
            list.Add(isPT() ? "Gasolina comum: 87 octanas" : "Nafta común: 87 octanos");
            list.Add(isPT() ? "Gasolina Aditiva Supra: 87 octanas (+ aditivos)" : "Nafta Aditiva Supra: 87 octanos (+ aditivitos)");
            list.Add(isPT() ? "Gasolina Premium: 91 octanas" : "Nafta Premium: 91 octanos");
            list.Add(isPT() ? "Gasolina Podium: 95 octanas" : "NaftaPodium: 95 octanos");

            MyList<string> listVisiveis = new MyList<string>();

            if (isPT())
            {
                listVisiveis.AddRange(new string[] { "6", "7", "8", "9"});
            }
            else
            {
                listVisiveis.AddRange(new string[] { "1", "2", "3", "4", "5"});
            }

            //listVisiveis.Shuffle();
            class_A.Lista = list;
            class_A.Visiveis = listVisiveis;
        }
Ejemplo n.º 11
0
        public void should_Get_Item_At_Index_From_MyList_Instance()
        {
            var myList = new MyList();
            myList.Add(1);
            myList.Add(2);
            myList.Add(3);
            myList.Add(4);
            myList.Add(5);

            var result = myList[4];
            Assert.AreEqual(5, result);
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            MyList<String> list = new MyList<String>();
            list.Add("Hello");
            list.Add("world");
            List<string> extractedList = list.GetArray<string>();

            for (int i = 0; i < extractedList.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
            Console.ReadKey();
        }
Ejemplo n.º 13
0
 static void Main(string[] args)
 {
     Auto auto = new Auto();
     MyList<Auto> myauto = new MyList<Auto>();
     myauto.Add(auto);
     myauto[0].Name = "Audi";
     myauto.Add(new Auto());
     foreach (Auto item in myauto)
     {
         Console.WriteLine(item.Name);
     }
     Console.WriteLine(myauto.Count);
     Console.ReadLine();
 }
Ejemplo n.º 14
0
        private void A36_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
            {
                return;
            }
            string msg = isPT() ? String.Format("Seu {0} é movido a que combustível?", rowCurrent["A4_A_NOME"]) : String.Format("¿Qué de combustible usa el motor de su {0}?", rowCurrent["A4_A_NOME"]);
            Label3.Text = msg;

            MyList<string> list = new MyList<string>();
            list.Add(isPT() ? "Gasolina" : "Nafta");
            list.Add(isPT() ? "Diesel" : "Diesel");
            list.Add(isPT() ? "GLP/ Gás de petróleo liquefeito mais gasolina " : "GLP/Gas Licuado de Petróleo más nafta");
            list.Add(isPT() ? "GNV ou Gás Natural Veicular mais gasolina" : "GNC/Gas Natural Comprimido más nafta");
            list.Add(isPT() ? "GNV ou Gás Natural Veicular" : "GNC/Gas Natural Comprimido");
            list.Add(isPT() ? "CNG/Compressed Natural Gasplus diesel" : "GNC/Gas Natural Comprimido");
            list.Add(isPT() ? "Flex / total flex: etanol e gasolina ou uma mistura dos dois" : "Combustible flexible (Flex fuel)/vehículo total flex: etanoly nafta o una mezcla de los mismos");
            list.Add(isPT() ? "Triflex/ Multiflex/ Nafta, gas más alcohol" : "Triflex/ Multiflex/ Nafta, gas más alcohol");

            MyList<string> listVisiveis = new MyList<string>();

            if (isPT())
            {
                listVisiveis.AddRange(new string[] { "1", "2", "4", "5", "7", "8", "9", "10", "11"});
            }
            else {
                listVisiveis.AddRange(new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" });
            }

            //listVisiveis.Shuffle();
            class_A.Lista = list;
            class_A.Visiveis = listVisiveis;
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            Auto auto = new Auto();
            Auto auto1 = new Auto();

            MyList<Auto> myauto = new MyList<Auto>();
            myauto.Add(auto);
            myauto[0].Name = "Audi";
            myauto.Add(auto1);
            myauto.Add(new Auto());
            // myauto.Remove(1);
            //Console.WriteLine(myauto[1].Name);
            myauto.GetArray<Auto>();
            Console.WriteLine(myauto.Count);
            Console.ReadLine();
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            var myList = new MyList<int>();

            int cnt = 11;
            for (int i = 0; i < cnt; i++)
            {
                myList.Add(i);
            }

            Console.WriteLine("List of elements: ");
            foreach (var item in myList)
            {
                Console.Write("{0}  ", item);
            }
            Console.WriteLine("| Count = {0}", myList.Count);

            myList.RemoveAt(5);
            myList.RemoveAt(5);
            myList.RemoveAt(5);

            Console.WriteLine("\nList of elements with removed elements: ");
            foreach (var item in myList)
            {
                Console.Write("{0}  ", item);
            }
            Console.WriteLine("| Count = {0}", myList.Count);

            Console.WriteLine("\nElement with index = 3:  {0}", myList[3]);

            Console.ReadKey();
        }
Ejemplo n.º 17
0
  public static void Main(String[] args) 
  {
    Console.WriteLine ("Fill MyList object with content\n");
    MyList l = new MyList();
    for (int x=0; x< 10; x++) 
    {
      Console.WriteLine (x);
      l.Add (x);
    } // end for
    Console.WriteLine("\nSerializing object graph to file {0}", FILENAME);
    Stream outFile = File.Open(FILENAME, FileMode.Create, FileAccess.ReadWrite);
    BinaryFormatter outFormat = new BinaryFormatter();
    outFormat.Serialize(outFile, l);
    outFile.Close();
    Console.WriteLine("Finished\n");

    Console.WriteLine("Deserializing object graph from file {0}", FILENAME);
    Stream inFile = File.Open(FILENAME, FileMode.Open, FileAccess.Read);
    BinaryFormatter inFormat = new BinaryFormatter();
    MyList templist = (MyList)inFormat.Deserialize(inFile);
    Console.WriteLine ("Finished\n");
    
    foreach (MyListItem mli in templist) 
    {
      Console.WriteLine ("List item number {0}, square root {1}", mli.Number, mli.Sqrt);
    } //foreach

    inFile.Close();
  } // end main
Ejemplo n.º 18
0
 public void should_Add_Single_Item_To_MyList_Instance()
 {
     var myList = new MyList();
     myList.Add(1);
     Assert.AreEqual(1,myList.Count);
     Assert.AreEqual(1,myList.Capacity);
 }
Ejemplo n.º 19
0
        public void Test16First()
        {
            MyList<MyPoint> set1 = new MyList<MyPoint>();
            set1.Add(new MyPoint(1, 6));
            set1.Add(new MyPoint(2, 6));
            set1.Add(new MyPoint(5, 6));
            set1.Add(new MyPoint(3, 6));
            set1.Add(new MyPoint(2, 5));
            set1.Add(new MyPoint(3, 5));
            set1.Add(new MyPoint(5, 5));
            set1.Add(new MyPoint(3, 4));
            set1.Add(new MyPoint(3, 7));
            set1.Add(new MyPoint(6, 4));
            set1.Add(new MyPoint(6, 5));
            set1.Add(new MyPoint(6, 6));
            set1.Add(new MyPoint(7, 5));
            set1.Add(new MyPoint(8, 5));
            set1.Add(new MyPoint(8, 4));
            set1.Add(new MyPoint(9, 6));

            ResultCollection2 res = Solution.CalculatePoints(set1);
            int val = res.ResultSet.Count;
            int permute = 0;
            Assert.IsTrue(val > 0);
            int c = res.ResultSet[0].Count;
            for (int i = 0; i < val; ++i)
            {
                Assert.AreEqual(c, res.ResultSet[i].Count);
                permute += res.ResultSet[i].Permutations;
            }

            Assert.AreEqual(8, val);
            Assert.AreEqual(192, permute);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Вернет список бьющихся фигур на проходе
        /// </summary>
        /// <returns></returns>
        public MyList<Position> GetInMoveAttacks()
        {
            int delta = (Side == Side.Black) ? +1 : -1;
            Position pos;
            Side oppside = GetEnemySide();
            Figure fig;
            MyList<Position> moves = new MyList<Position>();
            foreach (Position attack in GetAttacks())
            {
                try{
                    pos = new Position(attack.GetX(), attack.GetY() + delta);
                    fig = chessfield.GetFigureAt(pos);
                    if (fig != null && fig.GetFigureType() == FigureTypes.Pawn &&
                        fig.Side == oppside &&
                        chessfield.GetlastMoved(oppside) == fig)
                        moves.Add(pos);
                    {

                    }

                }
                catch {}

            }
            return moves;
        }
Ejemplo n.º 21
0
 public void AddTest()
 {
     var controlList = new System.Collections.Generic.List<int>();
     var testList = new MyList<int>();
     controlList.Add(1);
     testList.Add(1);
     Assert.AreEqual(controlList.Count, testList.Count);
 }
Ejemplo n.º 22
0
        public void ListRNDTest()
        {
            var controlList = new System.Collections.Generic.List<int>();
            var testList = new MyList<int>();

            var r = new System.Random();
            for (int i = 0; i < 1000; i++)
            {
                var next = r.Next();
                controlList.Add(next);
                testList.Add(next);
                Assert.AreEqual(controlList.Count, testList.Count);
            }
            for (int i = 0; i < 1000; i++)
            {
                Assert.IsTrue(testList.IndexOf(controlList[i]) == i);
            }
            for (int i = 0; i < controlList.Count; i++)
            {
                if (r.Next() < int.MaxValue / 2)
                {
                    testList.RemoveAt(i);
                    controlList.RemoveAt(i);
                }
                else
                {
                    var newItem = r.Next();
                    testList.Insert(i, newItem);
                    controlList.Insert(i, newItem);
                }
            }
            Assert.AreEqual(controlList.Count, testList.Count);

            foreach (var itm in controlList){
                Assert.IsTrue(testList.Contains(itm));
            }
            for (int i = 0; i < controlList.Count / 2; i++ )
            {
                var e = controlList[i];
                controlList.Remove(e);
                testList.Remove(e);
            }
            int[] controllarray = new int[controlList.Count+1];
            int[] testArray = new int[testList.Count+1];
            controllarray[0] = r.Next();
            testArray[0] = controllarray[0];
            controlList.CopyTo(controllarray, 1);
            testList.CopyTo(testArray, 1);

            var q = from a in testArray
                    join b in controllarray on a equals b
                    select a;

            Assert.IsTrue(testArray.Length == controllarray.Length && q.Count() == controllarray.Length);
            controlList.Clear();
            testList.Clear();
            Assert.AreEqual(controlList.Count,testList.Count);
        }
Ejemplo n.º 23
0
 static void TestList()
 {
     try
     {
         MyList<int> l = new MyList<int>();
         l.Add(5);
         l.Add(9);
         l.Add(10);
         Console.WriteLine(l.Get(23));
     }
     catch (ProgramException e)
     {
         Console.WriteLine(e.Message);
     }
     catch (Exception e)
     {
     }
 }
Ejemplo n.º 24
0
 private static void TestAdd(MyList<int> myList)
 {
     int[] testlist = new[] { 1, 3, 5, 7, 9 };
     for (int i = 0; i < testlist.Length; i++)
     {
         myList.Add(testlist[i]);
         Debug.Assert(myList.Contains(testlist[i]) == true, "List doesn't contain this number.");
     }
     Console.Write("New list: [{0}]", string.Join(", ", myList));
 }
Ejemplo n.º 25
0
 public override MyList<Position> GetMoves()
 {
     MyList<Position> moves = base.GetMoves();
        MyList<Position> newmoves = new MyList<Position>();
        Side oppositeside = GetEnemySide();
     foreach (Position pos in moves)
         if (!chessfield.isDangerPosition(oppositeside, pos,Position))
         // Fix situation of cyclic checking of two kings
         newmoves.Add(pos);
     return newmoves;
 }
Ejemplo n.º 26
0
        private void A45_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
            {
                return;
            }

            MyList<string> list = new MyList<string>();
            list.Add(isPT() ? "4 cilindros" : "Motor de 4cilindros");
            list.Add(isPT() ? "5 cilindros" : "Motor de 5 cilindros");
            list.Add(isPT() ? "6 cilindros" : "Motor de 6 cilindros");
            list.Add(isPT() ? "8 cilindros" : "Motor de 8 cilindros");
            list.Add(isPT() ? "10 cilindros" : "Motor de 10 cilindros");

            //List<string> listVisiveis = new List<string>();

            //listVisiveis.AddRange(new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14" });

            class_A.Lista = list;
            //class_A.Visiveis = listVisiveis;
        }
Ejemplo n.º 27
0
        public MyList<Position> GetMoves(Figure figure, ChessField cf)
        {
            Position pos = figure.Position;
            MyList<Position> l = new MyList<Position>();
            switch (figure.GetFigureType())
            {
                case FigureTypes.King:
                    {
                        if (pos.GetX() >1)
                            l.Add(new Position(pos.GetX()-1, pos.GetY()));
                        if (pos.GetX() < 8)
                            l.Add(new Position(pos.GetX()+1, pos.GetY()));
                        break;

                    }

                default: // Bishop, Queen & etc.
                    {
                        // +
                        for (int i = pos.GetX() + 1; i <= 8; i++)
                        {
                            l.Add(new Position(i, pos.GetY()));
                            if (cf.GetFigureAt(new Position(i, pos.GetY())) != null)
                                break;
                        }
                        // --
                        for (int i = pos.GetX() - 1; i > 0; i--)
                        {
                            l.Add(new Position( i, pos.GetY()));
                            if (cf.GetFigureAt(new Position( i, pos.GetY())) != null)
                                break;
                        }
                        break;
                    }
            }
            return l;
        }
Ejemplo n.º 28
0
        public void SpeedTest1()
        {
            for (int i = 0; i < 1000000; ++i)
            {
                MyList<MyPoint> set1 = new MyList<MyPoint>();
                set1.Add(new MyPoint(1, 6));
                set1.Add(new MyPoint(2, 5));
                set1.Add(new MyPoint(2, 6));
                set1.Add(new MyPoint(3, 4));
                set1.Add(new MyPoint(3, 5));
                set1.Add(new MyPoint(3, 6));
                set1.Add(new MyPoint(3, 7));
                set1.Add(new MyPoint(5, 5));
                set1.Add(new MyPoint(5, 6));
                set1.Add(new MyPoint(6, 4));

                Line currentLine = new Line();

                currentLine.AddValidPoint(set1[0]);
                currentLine.AddValidPoint(set1[1]);

                MyList<MyPoint> workSet = set1.Clone();

                workSet.RemoveAt(0);
                workSet.RemoveAt(1);

                int nPoints = workSet.Count;

                for (int k = nPoints - 1; k >= 0; k--)
                {
                    if (currentLine.AddValidPoint(workSet[k]))
                    {
                        workSet.RemoveAt(k);
                    }
                }
            }
        }
Ejemplo n.º 29
0
 public MyList<Position> GetMoves(Figure figure, ChessField cf)
 {
     Position pos = figure.Position;
     MyList<Position> l = new MyList<Position>();
     int x = pos.GetX(), y = pos.GetY();
     try
     {
         l.Add(new Position(x + 1, y + 2));
     }
     catch{}
     try
     {
         l.Add(new Position(x + 1, y + -2));
     }
     catch { }
     try
     {
         l.Add(new Position(x - 1, y + 2));
     }
     catch { }
     try
     {
         l.Add(new Position(x - 1, y - 2));
     }
     catch { }
     try
     {
         l.Add(new Position(x + 2, y + 1));
     }
     catch { }
     try
     {
         l.Add(new Position(x + 2, y - 1));
     }
     catch { }
     try
     {
         l.Add(new Position(x - 2, y +1));
     }
     catch { }
     try
     {
         l.Add(new Position(x -2, y - 1));
     }
     catch { }
     return l;
 }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            Console.WriteLine("首先尝试 MyList<int>  向  int[]  与  List<int> 进行转换.");

            // 测试对象.
            MyList<int> mylist1 = new MyList<int>();
            mylist1.Add(1);
            mylist1.Add(3);
            mylist1.Add(5);

            // 尝试 显式转换.
            int[] array1 = (int[])mylist1;

            // 尝试 隐式转换.
            List<int> list1 = mylist1;

            // 尝试比较.
            Console.WriteLine("mylist1 == array1 ? " + (mylist1 == array1));
            Console.WriteLine("mylist1 == list1 ? " + (mylist1 == list1));



            Console.WriteLine("然后尝试  int[]  与  List<int> 向 MyList<int> 进行转换.");
            int[] array2 = { 2, 4, 6 };
            // 尝试 显式转换.
            MyList<int> mylist2 = (MyList<int>)array2;
            // 尝试比较.
            Console.WriteLine("mylist2 == array2 ? " + (mylist2 == array2));


            List<int> list3 = new List<int>() {3,6,9};
            // 尝试 隐式转换.
            MyList<int> mylist3 = list3;
            Console.WriteLine("mylist3 == list3 ? " + (mylist3 == list3));

            Console.ReadLine();
        }
Ejemplo n.º 31
0
 public void AddToDictionary(TKey k, TValue v)
 {
     key.Add(k);
     value.Add(v);
 }
 public CurrentSerializableElements(ObjectSerial _base)
 {
     currents.Add(_base);
 }
Ejemplo n.º 33
0
        public void ListRNDTest()
        {
            System.Collections.Generic.IList <int> testList = new MyList <int>();
            var controlList = new System.Collections.Generic.List <int>();
            var r           = new System.Random();

            for (int i = 0; i < 1000; i++)
            {
                var next = r.Next();
                controlList.Add(next);
                testList.Add(next);
                Assert.Equal(controlList.Count, testList.Count);
            }
            for (int i = 0; i < 1000; i++)
            {
                Assert.True(testList.IndexOf(controlList[i]) == i);
            }
            foreach (var itm in controlList)
            {
                Assert.True(testList.Contains(itm));
            }

            for (int i = 0; i < controlList.Count; i++)
            {
                if (r.Next() < int.MaxValue / 2)
                {
                    testList.RemoveAt(i);
                    controlList.RemoveAt(i);
                }
                else
                {
                    var newItem = r.Next();
                    testList.Insert(i, newItem);
                    controlList.Insert(i, newItem);
                }
            }
            Assert.Equal(controlList.Count, testList.Count);


            foreach (var itm in controlList)
            {
                Assert.True(testList.Contains(itm));
            }
            for (int i = 0; i < controlList.Count / 2; i++)
            {
                var e = controlList[i];
                controlList.Remove(e);
                testList.Remove(e);
            }
            Assert.Equal(controlList.Count, testList.Count);

            int[] controllarray = new int[controlList.Count + 1];
            int[] testArray     = new int[testList.Count + 1];
            controllarray[0] = r.Next();
            testArray[0]     = controllarray[0];
            controlList.CopyTo(controllarray, 1);
            testList.CopyTo(testArray, 1);

            var q = from a in testArray
                    join b in controllarray on a equals b
                    select a;


            Assert.True(testArray.Length == controllarray.Length && q.Count() == controllarray.Length);
            controlList.Clear();
            testList.Clear();
            Assert.Equal(controlList.Count, testList.Count);
        }
Ejemplo n.º 34
0
        public void Add_AddItemToEmptyList_ListWithOneElement(T item)
        {
            lst.Add(item);

            Assert.Contains(item, lst.ToList());
        }
Ejemplo n.º 35
0
    public void f()
    {
        MyList <string> list = new MyList <string>(15);

        foreach (cv cv in PluginCore.cq.p.d())
        {
            if (list.Contains(cv.g()))
            {
                continue;
            }
            bool flag = false;
            switch (cv.c())
            {
            case ObjectClass.MeleeWeapon:
                flag = true;
                break;

            case ObjectClass.Armor:
                flag = true;
                break;

            case ObjectClass.Food:
                flag = true;
                list.Add(cv.g());
                break;

            case ObjectClass.MissileWeapon:
                flag = true;
                break;

            case ObjectClass.Gem:
                flag = true;
                list.Add(cv.g());
                break;

            case ObjectClass.ManaStone:
                flag = true;
                list.Add(cv.g());
                break;

            case ObjectClass.HealingKit:
                flag = true;
                list.Add(cv.g());
                break;

            case ObjectClass.WandStaffOrb:
                flag = true;
                break;
            }
            if (flag)
            {
                if (cv.j)
                {
                    this.a(cv.k, true);
                }
                else
                {
                    PluginCore.cq.u.a(cv.k, new b0.b(this.a), b0.a.a);
                }
            }
        }
        if (PluginCore.cq.u.b(b0.a.a) > 0)
        {
            PluginCore.e("Set default profile: Beginning inventory scan (" + PluginCore.cq.u.b(b0.a.a).ToString() + " items).");
            this.r = true;
        }
        else
        {
            PluginCore.e("Set default profile: Inventory scan not needed.");
        }
    }
Ejemplo n.º 36
0
 public void TestAdding()
 {
     _list.Add(0);
     Assert.AreEqual(_list.Count, 1);
     Assert.AreEqual(_list[0], 0);
     Assert.ThrowsException <IndexOutOfRangeException>(() => _list[1]);
 }
Ejemplo n.º 37
0
        static void Main()
        {
            {
                TestLogger.Log("Testing first- vs higher-kinded and mono- vs polymorphic-method combinations...");
                var l = new List <string>();
                l.Add("abc");
                TestLogger.Log(new FirstOrderClassPolymorphicMethod().Test(l));
                TestLogger.Log(new HigherKindedClassMonomorphicMethod <string>().Test(l));
                var dict = new Dictionary <string, int>();
                dict.Add("def", 3);
                TestLogger.Log(new HigherKindedClassPolymorphicMethod <string>().Test(dict));
            }

            {
                TestLogger.Log("Testing implicit implementations of interface methods on different instantiations of the same interface ...");
                TestSameInterfaceTwice <string>("test");
                TestSameInterfaceTwice <int>(1);
            }

            {
                TestLogger.Log("Testing implicit and explicit implementations of interface methods on the same interface...");
                var x = new ImplicitAndExplicit <string>();
                x.Test1(new Wrapper <string>("hij"));
                ITwoTests <Wrapper <string> > y = x;
                y.Test2(new Wrapper <string>("klm"));
            }

            {
                TestLogger.Log("Testing construction and field mutation...");
                var p = new Person("pqr");
                TestLogger.Log(p.ToString());

                var b1 = new MyBox <Person, string>(new Person("opq"));
                b1.u = "b1";
                var b2 = new MyBox <int, string>(1);
                b2.u = "b2";

                TestLogger.Log(b1.ToString());
                TestLogger.Log(b2.ToString());

                b1.t = new Person("rst");
                b1.u = "uvw";
                b2.t = 3;

                TestLogger.Log(b1.ToString());
                TestLogger.Log(b2.ToString());
            }

            {
                TestLogger.Log("Testing mini generic lists of object...");
                var list = new MyList <object>();
                list.Add(1);
                list.Add("2");
                list.Add(new Person("pqr"));
                foreach (var obj in list)
                {
                    TestLogger.Log(obj.ToString());
                }
            }

            {
                TestLogger.Log("Testing mini generic dictionary of string to int...");
                var dict = new MyDictionary <string, int>();
                dict.Add("one", 1);
                dict.Add("two", 2);
                dict.Add("three", 3);
                foreach (var kvPair in dict)
                {
                    TestLogger.Log(kvPair.Key + " -> " + kvPair.Value);
                }
            }

            {
                TestLogger.Log("Testing static fields on distinct type instances...");
                MyList <int> .testVal    = 1;
                MyList <string> .testVal = 2;

                TestLogger.Log(MyList <int> .testVal.ToString());
                TestLogger.Log(MyList <string> .testVal.ToString());
            }

            {
                TestLogger.Log("Testing generic methods with interesting permutation of type arguments..");;
                var b = new MyBox <Person, string>(new Person("opq"));
                b.u = "second";
                TestGenericMethod <Person, string, int>(b, 5, null);
                TestGenericMethod <Person, string, string>(b, "xyz", null);
                TestGenericMethod <Person, string, Person>(b, new Person("efg"), null);
            }

            {
                TestLogger.Log("Testing recursive types...");
                var a = new A <B>();
                var b = new B();
                TestLogger.Log(a.M(b));
                TestLogger.Log(b.M(a));
            }
        }
Ejemplo n.º 38
0
        public void AddIntTestLargeSize()
        {
            //arrange
            MyList<int> numberTest = new MyList<int>();

            //act
            numberTest.Add(0);
            numberTest.Add(1);
            numberTest.Add(2);
            numberTest.Add(3);
            numberTest.Add(4);
            numberTest.Add(5);
            numberTest.Add(6);
            numberTest.Add(7);
            numberTest.Add(8);
            numberTest.Add(9);
            numberTest.Add(10);
            numberTest.Add(11);
            numberTest.Add(12);
            numberTest.Add(13);
            numberTest.Add(14);
            numberTest.Add(15);

            //assert
            Assert.AreEqual(16, numberTest.Count);
        }
Ejemplo n.º 39
0
        public void AddToListWithPresetCapacityTest()
        {
            MyList <int> a = new MyList <int>(10);

            a.Add(5);
            a.Add(6);
            a.Add(7);
            a.Add(8);
            a.Add(9);
            a.Add(10);
            a.Add(11);
            a.Add(12);
            a.Add(13);
            a.Add(14);
            a.Add(15);
            a.Add(16);
            a.Insert(2, 123);
            Assert.AreEqual(8, a[4]);
        }
Ejemplo n.º 40
0
 public void Add(int number)
 {
     sl.Add(number);
     l.Add(number);
 }
Ejemplo n.º 41
0
        public void ChekcingIndexInt()
        {
            //arrange
            MyList<int> numberTest = new MyList<int>();

            //act
            numberTest.Add(0);
            numberTest.Add(1);
            numberTest.Add(2);
            numberTest.Add(3);
            numberTest.Add(4);
            numberTest.Add(5);
            numberTest.Add(6);
            numberTest.Add(7);
            numberTest.Add(8);
            numberTest.Add(9);
            numberTest.Add(10);
            numberTest.Add(11);
            numberTest.Add(12);
            numberTest.Add(13);
            numberTest.Add(14);
            numberTest.Add(15);

            //assert
            Assert.AreEqual(10, numberTest[10]);
        }
Ejemplo n.º 42
0
        public void AddingToCapacity()
        {
            //arrange
            int expected = 15;

            //act
            MyList <int> mylist = new MyList <int>();

            mylist.Add(63);
            mylist.Add(102);
            mylist.Add(23);
            mylist.Add(67);
            mylist.Add(33);
            mylist.Add(69);
            mylist.Add(63);
            mylist.Add(102);
            mylist.Add(23);
            mylist.Add(67);
            mylist.Add(33);
            mylist.Add(69);

            //assert
            Assert.AreEqual(expected, mylist.Capacity);
        }
Ejemplo n.º 43
0
    static void Main()
    {
        var line = Console.ReadLine();

        string element;
        int    index;

        var myCustomList = new MyList <string>();

        while (!line.Equals("END"))
        {
            var commandArgs = line.Split();

            var action = commandArgs[0];

            switch (action)
            {
            case "Add":
                element = commandArgs[1];

                myCustomList.Add(element);
                break;

            case "Remove":
                index = int.Parse(commandArgs[1]);

                myCustomList.Remove(index);
                break;

            case "Contains":
                element = commandArgs[1];

                var containsElement = myCustomList.Contains(element);

                Console.WriteLine(containsElement ? "True" : "False");
                break;

            case "Swap":
                var firstIndex  = int.Parse(commandArgs[1]);
                var secondIndex = int.Parse(commandArgs[2]);

                myCustomList.Swap(firstIndex, secondIndex);
                break;

            case "Greater":
                element = commandArgs[1];

                var count = myCustomList.CountGraterThan(element);

                Console.WriteLine(count);
                break;

            case "Max":
                var maxElement = myCustomList.Max();

                Console.WriteLine(maxElement);
                break;

            case "Min":
                var minElement = myCustomList.Min();

                Console.WriteLine(minElement);
                break;

            case "Sort":
                myCustomList.Sort();
                break;

            case "Print":
                Console.WriteLine(myCustomList.ToString());
                break;
            }

            line = Console.ReadLine();
        }
    }
Ejemplo n.º 44
0
 public void Add(MyClass item)
 {
     _myList.Add(item);
 }
Ejemplo n.º 45
0
        public void AddTestMethod()
        {
            Assert.AreNotEqual(null, list);
            Assert.AreEqual(0, list.Count);
            list.Add(10);
            Assert.AreEqual(1, list.Count);

            for (int i = 0; i < 100; ++i)
            {
                list.Add(i);
            }
            Assert.AreEqual(101, list.Count);
        }
Ejemplo n.º 46
0
        public void Add_OneItem_MyListShouldContainsThisItem()
        {
            myList.Add(1);

            myList.Should().ContainSingle(item => item == 1);
        }
Ejemplo n.º 47
0
 public void Add(K key, V value)
 {
     list.Add(new MyKeyValuePair <K, V>(key, value));
 }
Ejemplo n.º 48
0
        public override void appendElementSerialWithoutRef(MyList <ElementsSerial> _elt)
        {
            keys   = new MyList <object>();
            values = new MyList <object>();
            MethodInfo ADD_METHOD = value.GetType().GetMethod("Add", types);

            foreach (ElementsSerial e in _elt)
            {
                if (e is ComparatorSerial)
                {
                    continue;
                }
                Type   t_        = typeof(IEnumerable);
                string fullType_ = Constants.getTypeFullString(t_);
                if (fullType_.ToLower().Equals(e.getClassName().ToLower()))
                {
                    object obj_ = e.getValue();

                    /*if (obj_ != null)
                     * {
                     *  if (obj_.GetType().IsPrimitive)
                     *  {
                     *      if (types.ElementAt(0).IsEnum)
                     *      {
                     *          throw new ArgumentException();
                     *          //Console.WriteLine("%%%"+ obj_);
                     *      }
                     *  }
                     *  if (types.ElementAt(0).IsPrimitive)
                     *  {
                     *      if (obj_.GetType().IsEnum)
                     *      {
                     *          throw new ArgumentException();
                     *          //Console.WriteLine("%%%"+ obj_);
                     *      }
                     *  }
                     * }*/
                    ADD_METHOD.Invoke(value, new object[] { obj_ });
                    continue;
                }

                /*if (typeof(IEnumerable).FullName.ToLower().Equals(e.getClassName().ToLower()))
                 * {
                 *                  ADD_METHOD.Invoke(value, new object[] { e.getValue() });
                 *                  continue;
                 *          }*/
            }
            foreach (ElementsSerial e in _elt)
            {
                if (e is ComparatorSerial)
                {
                    cmpSerial = (ComparatorSerial)e;
                    continue;
                }
                Type   t_        = typeof(ListableKey);
                string fullType_ = Constants.getTypeFullString(t_);
                if (!fullType_.ToLower().Equals(e.getClassName().ToLower()))
                {
                    continue;
                }
                object obj_ = e.getValue();

                /*if (!typeof(ListableKey).FullName.ToLower().Equals(e.getClassName().ToLower()))
                 * {
                 *  continue;
                 * }*/
                /*if (!e.getClassName().equalsIgnoreCase(Map.class.getName())) {
                 *              continue;
                 *          }*/
                if (!e.isKeyOfMap())
                {
                    /*if (obj_ != null)
                     * {
                     *  if (obj_.GetType().IsPrimitive)
                     *  {
                     *      if (types.ElementAt(1).IsEnum)
                     *      {
                     *          throw new ArgumentException();
                     *          //Console.WriteLine("%%%"+ obj_);
                     *      }
                     *  }
                     *  if (types.ElementAt(1).IsPrimitive)
                     *  {
                     *      if (obj_.GetType().IsEnum)
                     *      {
                     *          throw new ArgumentException();
                     *          //Console.WriteLine("%%%"+ obj_);
                     *      }
                     *  }
                     * }*/
                    values.Add(e.getValue());
                }
                else
                {
                    /*if (obj_ != null)
                     * {
                     *  if (obj_.GetType().IsPrimitive)
                     *  {
                     *      if (types.ElementAt(0).IsEnum)
                     *      {
                     *          throw new ArgumentException();
                     *          //Console.WriteLine("%%%"+ obj_);
                     *      }
                     *  }
                     *  if (types.ElementAt(0).IsPrimitive)
                     *  {
                     *      if (obj_.GetType().IsEnum)
                     *      {
                     *          throw new ArgumentException();
                     *          //Console.WriteLine("%%%"+ obj_);
                     *      }
                     *  }
                     * }*/
                    keys.Add(e.getValue());
                }
            }
            foreach (ElementsSerial e in _elt)
            {
                if (e is ComparatorSerial)
                {
                    continue;
                }
                Type   t_        = typeof(IEnumerable);
                string fullType_ = Constants.getTypeFullString(t_);
                //Console.WriteLine(e.getClassName() + "%%" + fullType_);

                /*Type t2_ = typeof(IEnumerable);
                 * string str2_ = ElementsSerial.getType(t_);
                 * string assName2_ = t_.Assembly.GetName().Name;
                 * string fullType2_ = assName_ + ".." + str_;*/
                if (fullType_.ToLower().Equals(e.getClassName().ToLower()))
                {
                    continue;
                }
                t_        = typeof(ListableKey);
                fullType_ = Constants.getTypeFullString(t_);
                if (fullType_.ToLower().Equals(e.getClassName().ToLower()))
                {
                    continue;
                }

                /*if (typeof(IEnumerable).FullName.ToLower().Equals(e.getClassName().ToLower()))
                 * {
                 *  continue;
                 * }
                 * if (typeof(ListableKey).FullName.ToLower().Equals(e.getClassName().ToLower()))
                 * {
                 *  continue;
                 * }*/
                /*if (e.getClassName().equalsIgnoreCase(List.class.getName())) {
                 *                  continue;
                 *          }
                 *          if (e.getClassName().equalsIgnoreCase(Map.class.getName())) {
                 *                  continue;
                 *          }*/
                //Type class_ = Constants.classForName(e.getClassName());
                string str_ = e.getClassName();
                Type   class_;
                if (str_.Contains(SPECIAL_SEP))
                {
                    string types_ = str_.Substring(str_.IndexOf(SPECIAL_SEP));
                    class_ = Constants.classForName(str_, types_);
                }
                else
                {
                    class_ = Constants.classForName(str_);
                }
                if (!class_.IsInstanceOfType(value))
                {
                    continue;
                }

                /*FieldInfo field_ = class_.GetField(e.getField(), BindingFlags.NonPublic |
                 * BindingFlags.Instance);*/
                FieldInfo field_ = SerializeXmlObject.getField(class_, e.getField());
                object    obj_   = e.getValue();

                /*if (obj_ != null)
                 * {
                 *  if (obj_.GetType().IsPrimitive)
                 *  {
                 *      if (field_.FieldType.IsEnum)
                 *      {
                 *          throw new ArgumentException();
                 *          //Console.WriteLine("%%%"+ obj_);
                 *      }
                 *  }
                 *  if (obj_.GetType().IsEnum)
                 *  {
                 *      if (field_.FieldType.IsPrimitive)
                 *      {
                 *          throw new ArgumentException();
                 *          //Console.WriteLine("%%%"+ obj_);
                 *      }
                 *  }
                 * }*/
                /*if (!SerializeXmlObject.isUpdateFinalFields()) {
                 *                  if (Modifier.isFinal(field_.getModifiers())) {
                 *                          continue;
                 *                  }
                 *          }
                 *          if (Modifier.isStatic(field_.getModifiers())) {
                 *                  continue;
                 *          }*/
                //field_.setAccessible(class_.getAnnotation(RwXml.class)!=null);

                field_.SetValue(value, e.getValue());
            }
            if (value is ListableKey && !(value is IComparableKeys))
            {
                FieldInfo LIST_FIELD = value.GetType().GetField("list", BindingFlags.NonPublic |
                                                                BindingFlags.Instance);
                Object list_ = LIST_FIELD.GetValue(value);
                ADD_METHOD = list_.GetType().GetMethod("Add");
                Type treeMapTypeGene_ = typeof(Map <,>);
                //string treeMapType_ = treeMapTypeGene_.Assembly.GetName().Name + ".." + treeMapTypeGene_.Namespace + "." + treeMapTypeGene_.Name;
                string treeMapType_ = treeMapTypeGene_.Assembly.GetName().Name + "." + treeMapTypeGene_.Namespace + "." + treeMapTypeGene_.Name;
                treeMapType_ = treeMapType_.Substring(0, treeMapType_.IndexOf(ElementsSerial.SPECIAL_SEP) + 1);
                Type curType_ = value.GetType();
                while (true)
                {
                    if (curType_ == null)
                    {
                        break;
                    }
                    if (Constants.getTypeFullString(curType_).StartsWith(treeMapType_))
                    {
                        break;
                    }
                    curType_ = curType_.BaseType;
                }
                Type[]          args_        = curType_.GetGenericArguments();
                Type            genericType_ = typeof(Entry <,>).MakeGenericType(args_);
                ConstructorInfo ctor_        = genericType_.GetConstructor(args_);
                int             len_         = keys.size();
                for (int i = 0; i < len_; i++)
                {
                    //PUT_METHOD.invoke(value, keys.get(i),values.get(i));
                    object e_ = ctor_.Invoke(new object[] { keys.get(i), values.get(i) });
                    ADD_METHOD.Invoke(list_, new object[] { e_ });
                }
                keys.Clear();
                values.Clear();
            }
            if (value is IComparableKeys)
            {
                Type treeMapTypeGene_ = typeof(TreeMap <,>);
                //string treeMapType_ = treeMapTypeGene_.Assembly.GetName().Name + ".." + treeMapTypeGene_.Namespace + "." + treeMapTypeGene_.Name;
                string treeMapType_ = treeMapTypeGene_.Assembly.GetName().Name + "." + treeMapTypeGene_.Namespace + "." + treeMapTypeGene_.Name;
                treeMapType_ = treeMapType_.Substring(0, treeMapType_.IndexOf(ElementsSerial.SPECIAL_SEP) + 1);
                Type curType_ = value.GetType();
                while (true)
                {
                    if (curType_ == null)
                    {
                        break;
                    }
                    if (Constants.getTypeFullString(curType_).StartsWith(treeMapType_))
                    {
                        break;
                    }
                    curType_ = curType_.BaseType;
                }
                Type[] args_ = curType_.GetGenericArguments();
                if (cmpSerial != null)
                {
                    Type dicoMapType_;    // = typeof(SortedDictionary<,>);
                    Type speTreeMapType_; // = dicoMapType_.MakeGenericType(args_);

                    /*foreach (PropertyInfo p in SerializeXmlObject.getProperties(speTreeMapType_))
                     * {
                     *  Console.WriteLine(p.Name);
                     * }*/
                    //PropertyInfo p_ = SerializeXmlObject.getProperty(speTreeMapType_, COMPARATOR);
                    //f_.setAccessible(true);
                    //Console.WriteLine(cmpSerial.getValue().GetType());
                    //Console.WriteLine(p_.PropertyType);
                    //p_.GetSetMethod(true)
                    //p_.GetSetMethod(true).Invoke(value, new object[] { cmpSerial.getValue() });
                    //p_.SetValue(value, cmpSerial.getValue());
                    dicoMapType_    = typeof(TreeMap <,>);
                    speTreeMapType_ = dicoMapType_.MakeGenericType(args_);
                    FieldInfo f_ = SerializeXmlObject.getField(speTreeMapType_, "comparator");
                    //f_.setAccessible(true);
                    f_.SetValue(value, cmpSerial.getValue());
                }
                MethodInfo m_   = curType_.GetMethod("put", args_);
                int        len_ = keys.size();
                for (int i = 0; i < len_; i++)
                {
                    m_.Invoke(value, new object[] { keys.get(i), values.get(i) });
                }
                keys.Clear();
                values.Clear();
            }

            /*if (PairUtil.isMap(value)) {
             *
             * }*/
        }
Ejemplo n.º 49
0
        static void Main(string[] args)
        {
            MyList <int> myList = new MyList <int>()
            {
                1, 2, 3
            };

            // Demo Enumerator
            Console.WriteLine("Demo Enumerator");

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            // Demo Resize and Capacity
            Console.WriteLine("Demo Resize and Capacity");

            var currentCapacity = myList.Capacity;

            for (int i = 0; i < 500; i++)
            {
                myList.Add(i);

                if (currentCapacity != myList.Capacity)
                {
                    Console.WriteLine($"Resized too {myList.Capacity}");

                    currentCapacity = myList.Capacity;
                }
            }

            // Demo Resize and Initial Capacity
            Console.WriteLine("Demo Resize and Initial Capacity");

            myList = new MyList <int>(500)
            {
                1
            };

            currentCapacity = myList.Capacity;

            for (int i = 0; i < 500; i++)
            {
                myList.Add(i);

                if (currentCapacity != myList.Capacity)
                {
                    Console.WriteLine($"Resized too {myList.Capacity}");

                    currentCapacity = myList.Capacity;
                }
            }

            // Demo TrimExcess
            Console.WriteLine("Demo TrimExcess");

            currentCapacity = myList.Capacity;

            myList.TrimExcess();

            Console.WriteLine($"Trimmed from {currentCapacity} to {myList.Capacity}");

            // Demo Clear
            Console.WriteLine("Demo Clear");

            var currentCount = myList.Count;

            myList.Clear();

            Console.WriteLine($"Cleared from count {currentCount} to {myList.Count}");

            // Demo Add
            Console.WriteLine("Demo Add");

            myList = new MyList <int>(3)
            {
                1, 2, 3
            };

            myList.Add(5000);

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {myList.Count}");

            // Demo AddRange
            Console.WriteLine("Demo AddRange");

            myList = new MyList <int>(3)
            {
                1, 2, 3
            };

            myList.AddRange(new [] { 10, 10, 10, 10, 10, 10, 10 });

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {myList.Count}");

            // Demo Insert
            Console.WriteLine("Demo Insert");

            myList = new MyList <int>(3)
            {
                1, 2, 3
            };

            myList.Insert(2, 2500);
            myList.Insert(4, 2500);

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {myList.Count}");

            // Demo InsertRange
            Console.WriteLine("Demo InsertRange");

            // Performance Tests (see region tags in InsertRange())
            // Comparison between Copy then Shuffle experiment
            // Comparison between giving up CPU vs Memory experiment
            // myList = new MyList<int>();

            // int[] aBunchOfItems = Enumerable.Range(0, 100000000).ToArray();

            // myList.AddRange(aBunchOfItems);

            // Stopwatch timer = new Stopwatch();

            // timer.Start();

            // myList.InsertRange(5, aBunchOfItems);

            // timer.Stop();

            // Console.WriteLine(timer.ElapsedTicks / (float)Stopwatch.Frequency);
            // Console.WriteLine($"New Count: {myList.Count}");

            myList = new MyList <int>()
            {
                1, 2, 3
            };

            myList.InsertRange(1, new [] { 10, 10, 10, 10, 10, 10, 10 });

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {myList.Count}");

            // Demo GetRange
            Console.WriteLine("Demo GetRange");

            myList = new MyList <int>()
            {
                0, 1, 2, 3, 4, 5, 6
            };

            var index        = 2;
            var returnedList = myList.GetRange(index, myList.Count - index);

            foreach (int item in returnedList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {returnedList.Count}");

            // Demo RemoveAt
            Console.WriteLine("Demo RemoveAt");

            myList = new MyList <int>()
            {
                0, 1, 2, 3, 4, 5, 6
            };

            myList.RemoveAt(3);

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {myList.Count}");

            // Demo Remove
            Console.WriteLine("Demo Remove");

            myList = new MyList <int>()
            {
                0, 1, 0, 1, 0
            };

            myList.Remove(1);

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {myList.Count}");

            // Demo RemoveAll
            Console.WriteLine("Demo RemoveAll");

            myList = new MyList <int>()
            {
                2, 0, 1, 0, 5
            };

            myList.RemoveAll(x => x > 0);

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {myList.Count}");

            // Demo RemoveRange
            Console.WriteLine("Demo RemoveRange");

            myList = new MyList <int>()
            {
                2, 0, 0, 0, 5
            };

            myList.RemoveRange(1, 3);

            foreach (int item in myList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"New Count: {myList.Count}");

            // Demo TrueForAll
            Console.WriteLine("Demo TrueForAll");

            myList = new MyList <int>()
            {
                1, 2, 3
            };

            Console.WriteLine(myList.TrueForAll(x => x < 4));
            Console.WriteLine(myList.TrueForAll(x => x > 1));

            // Demo Exists
            Console.WriteLine("Demo Exists");

            myList = new MyList <int>()
            {
                1, 2, 3
            };

            Console.WriteLine(myList.Exists(x => x > 1));
            Console.WriteLine(myList.Exists(x => x > 3));

            // Demo ConvertAll
            Console.WriteLine("Demo ConvertAll");

            myList = new MyList <int>()
            {
                1, 2, 3
            };

            MyList <string> myListString = myList.ConvertAll(x => x.ToString());

            myListString.ForEach(x =>
            {
                Console.WriteLine(x is string);
                Console.WriteLine(x);
            });

            // Demo Find and FindLast
            Console.WriteLine("Demo Find and FindLast and FindAll");

            myList = new MyList <int>()
            {
                1, 4, 2, 3, 1, 2, 3, 4, 3, 4, 3
            };

            Console.WriteLine(myList.Find(x => x == 3));
            Console.WriteLine(myList.FindLast(x => x == 4));

            var allItems = myList.FindAll(x => x == 3);

            allItems.ForEach(x => Console.WriteLine(x));
        }
Ejemplo n.º 50
0
 public void TestToStr()
 {
     _list.Add(1);
     _list.Add(2);
     _list.Add(3);
     _list.Add(4);
     Assert.AreEqual("1234", _list.ToString());
 }
Ejemplo n.º 51
0
        public static XmlDocument getSource(Object _serialisable)
        {
            //XmlDocument document_ = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            XmlDocument document_ = new XmlDocument();

            try {
                ElementsSerial primitive_;
                primitive_ = CurrentSerializableElements.createPrimitive(_serialisable);
                if (primitive_ != null)
                {
                    XmlElement elt_ = primitive_.serializeWithoutRef(document_);
                    document_.AppendChild(elt_);
                    return(document_);
                }
            } catch (Exception) {
            }
            //XmlNode firstNode_ = document_.CreateElement(_serialisable.GetType().FullName);
            //XmlNode firstNode_ = document_.CreateElement(_serialisable.GetType().FullName.Split(new string[] { "`" }, StringSplitOptions.None)[0]);
            ObjectSerial base_ = new ObjectSerial(_serialisable);

            //XmlNode firstNode_ = document_.CreateElement(ElementsSerial.getTypeName(_serialisable));
            XmlNode firstNode_ = base_.serializeWithoutRef(document_);

            document_.AppendChild(firstNode_);
            MyList <XmlNode> currentNodesToBeCompleted_ = new MyList <XmlNode>();

            currentNodesToBeCompleted_.Add(firstNode_);

            CurrentSerializableElements currentThread_ = new CurrentSerializableElements(base_);

            currentThread_.initializeObjectsWithoutIdRef();
            MyList <TemplateSerial> currentSerializableElements_ = new MyList <TemplateSerial>();

            currentSerializableElements_.Add(base_);
            MyList <XmlNode>        newNodesToBeCompleted_   = new MyList <XmlNode>();
            MyList <TemplateSerial> newSerializableElements_ = new MyList <TemplateSerial>();
            bool modif_ = true;

            while (modif_)
            {
                modif_ = false;
                newSerializableElements_ = new MyList <TemplateSerial>();
                newNodesToBeCompleted_   = new MyList <XmlNode>();
                int len_;
                len_ = currentNodesToBeCompleted_.size();
                for (int i = List.FIRST_INDEX; i < len_; i++)
                {
                    XmlNode               currentNode_         = currentNodesToBeCompleted_.get(i);
                    TemplateSerial        currentSerializable_ = currentSerializableElements_.get(i);
                    List <ElementsSerial> elts_ = currentThread_.getComponentComposite(currentSerializable_);
                    foreach (ElementsSerial e in elts_)
                    {
                        XmlNode newNode_ = e.serializeWithoutRef(document_);
                        if (e is TemplateSerial && !(e is EnumSerial))
                        {
                            TemplateSerial t_ = (TemplateSerial)e;
                            if (t_.getRef() == null)
                            {
                                newNodesToBeCompleted_.Add(newNode_);
                                newSerializableElements_.Add(t_);
                            }
                        }
                        currentNode_.AppendChild(newNode_);
                    }
                }
                if (!newSerializableElements_.isEmpty())
                {
                    currentNodesToBeCompleted_   = new MyList <XmlNode>(newNodesToBeCompleted_);
                    currentSerializableElements_ = new MyList <TemplateSerial>(newSerializableElements_);
                    modif_ = true;
                }
            }
            return(document_);
        }
Ejemplo n.º 52
0
        public static Object fromXmlStringObject(String _xmlString)
        {
            XmlElement root_ = XmlParser.documentElement(XmlParser.parseSax(_xmlString));

            try {
                ElementsSerial elt_ = createPrimitive(root_);
                if (elt_ != null)
                {
                    return(elt_.getValue());
                }
            } catch (Exception) {
            }
            MyList <XmlNode> currentNodesToBeRead_ = new MyList <XmlNode>();

            currentNodesToBeRead_.Add(root_);
            MyList <TemplateSerial> currentSerializableElements_ = new MyList <TemplateSerial>();
            ObjectSerial            rootElement_;

            rootElement_ = ObjectSerial.newSerial(root_, false);
            currentSerializableElements_.Add(rootElement_);
            MyList <XmlNode>        newNodesToBeRead_        = new MyList <XmlNode>();
            MyList <TemplateSerial> newSerializableElements_ = new MyList <TemplateSerial>();
            MyList <ObjectSerial>   notEmptyMaps_            = new MyList <ObjectSerial>();
            bool modif_ = true;

            while (modif_)
            {
                modif_ = false;
                newSerializableElements_ = new MyList <TemplateSerial>();
                newNodesToBeRead_        = new MyList <XmlNode>();
                int len_;
                len_ = currentNodesToBeRead_.size();
                for (int i = List.FIRST_INDEX; i < len_; i++)
                {
                    XmlNode        currentNode_  = currentNodesToBeRead_.get(i);
                    TemplateSerial composite_    = currentSerializableElements_.get(i);
                    bool           isTreeMap_    = false;
                    bool           containsTree_ = false;
                    foreach (XmlNode nCh_ in XmlParser.childrenNodes(currentNode_))
                    {
                        if (!(nCh_ is XmlElement))
                        {
                            continue;
                        }
                        containsTree_ = nCh_.Attributes.GetNamedItem(TemplateSerial.COMPARATOR) != null;
                        if (containsTree_)
                        {
                            break;
                        }
                    }
                    if (containsTree_)
                    {
                        isTreeMap_ = true;
                    }
                    MyList <ElementsSerial> elt_ = new MyList <ElementsSerial>();
                    foreach (XmlNode n in XmlParser.childrenNodes(currentNode_))
                    {
                        if (!(n is XmlElement))
                        {
                            continue;
                        }
                        try
                        {
                            ArraySerial serialArray_ = ArraySerial.newListSerial(n);
                            elt_.Add(serialArray_);
                            newSerializableElements_.Add(serialArray_);
                            newNodesToBeRead_.Add(n);
                            continue;
                        }
                        catch (NoAttributeForSerializable e_)
                        {
                            throw e_;
                        }
                        catch (ClassFoundException)
                        {
                        }
                        try
                        {
                            ElementsSerial primitive_ = createPrimitive(n);
                            if (primitive_ == null)
                            {
                                throw new NullReferenceException();
                            }
                            elt_.Add(primitive_);
                            continue;
                        }
                        catch (NoAttributeForSerializable e_)
                        {
                            throw e_;
                        }
                        catch (InexistingValueForEnum e_)
                        {
                            throw e_;
                        }
                        catch (FormatException e_)
                        {
                            throw e_;
                        }

                        /*catch (InvocationTargetException e_)
                         * {
                         *  throw e_;
                         * }
                         * catch (InstantiationException e_)
                         * {
                         *  throw e_;
                         * }
                         * catch (SecurityException e_)
                         * {
                         *  throw e_;
                         * }
                         * catch (ClassNotFoundException e_)
                         * {
                         *  throw e_;
                         * }*/
                        catch (NullReferenceException)
                        {
                        }
                        ComparatorSerial cmp_ = getCmpSerial(n, isTreeMap_, composite_);
                        if (cmp_ != null)
                        {
                            elt_.Add(cmp_);
                            newSerializableElements_.Add(cmp_);
                            newNodesToBeRead_.Add(n);
                            continue;
                        }
                        ObjectSerial serial_ = ObjectSerial.newSerial(n, true);
                        elt_.Add(serial_);
                        newSerializableElements_.Add(serial_);
                        newNodesToBeRead_.Add(n);
                    }
                    composite_.appendElementSerialWithoutRef(elt_);
                    if (composite_ is ObjectSerial)
                    {
                        if (!((ObjectSerial)composite_).mapIsEmpty())
                        {
                            notEmptyMaps_.Add((ObjectSerial)composite_);
                        }
                    }
                }
                if (!newSerializableElements_.isEmpty())
                {
                    currentNodesToBeRead_        = new MyList <XmlNode>(newNodesToBeRead_);
                    currentSerializableElements_ = new MyList <TemplateSerial>(newSerializableElements_);
                    modif_ = true;
                }
            }
            List <ObjectSerial> filledMaps_   = new MyList <ObjectSerial>();
            List <ObjectSerial> fillableMaps_ = new MyList <ObjectSerial>();

            /*foreach (ObjectSerial m in notEmptyMaps_) {
             *      if (m.keysAllDifferent()) {
             *              fillableMaps_.Add(m);
             *      }
             * }
             * while (true) {
             *      for (MayBeMap m : fillableMaps_) {
             *              m.setComponents();
             *              filledMaps_.add(m);
             *      }
             *      fillableMaps_.clear();
             *      for (MayBeMap m : notEmptyMaps_) {
             *              if (!m.keysAllDifferent()) {
             *                      continue;
             *              }
             *              if (filledMaps_.containsObj(m)) {
             *                      continue;
             *              }
             *              fillableMaps_.add(m);
             *      }
             *      if (fillableMaps_.isEmpty()) {
             *              break;
             *      }
             * }
             * for (MayBeMap m : notEmptyMaps_) {
             *      if (!filledMaps_.containsObj(m)) {
             *              m.setComponents();
             *      }
             * }*/
            return(rootElement_.getValue());
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Agregar un elemento al stack
 /// </summary>
 /// <param name="element"></param>
 public void Push(T element)
 {
     internalList.Add(element);
 }
Ejemplo n.º 54
0
        public override void appendElementSerial(MyList <ElementsSerial> _elt)
        {
            indexesRef = new Map <int?, long?>();
            int i_ = 0;

            keys           = new MyList <object>();
            keysIndexesRef = new Map <int?, long?>();
            int iKey_ = 0;

            values           = new MyList <object>();
            valuesIndexesRef = new Map <int?, long?>();
            int        iValue_    = 0;
            MethodInfo ADD_METHOD = value.GetType().GetMethod("Add");

            foreach (ElementsSerial e in _elt)
            {
                if (e is ComparatorSerial)
                {
                    continue;
                }
                if (typeof(IEnumerable).FullName.ToLower().Equals(e.getClassName().ToLower()))
                {
                    if (e is TemplateSerial)
                    {
                        if (((TemplateSerial)e).getRef() != null)
                        {
                            indexesRef.put(i_, ((TemplateSerial)e).getRef());
                        }
                    }
                    ADD_METHOD.Invoke(value, new object[] { e.getValue() });
                    i_++;
                    continue;
                }
            }
            foreach (ElementsSerial e in _elt)
            {
                if (e is ComparatorSerial)
                {
                    cmpSerial = (ComparatorSerial)e;
                    continue;
                }
                //ListableKey
                //
                if (!typeof(ListableKey).FullName.ToLower().Equals(e.getClassName().ToLower()))
                {
                    continue;
                }

                /*if (!e.getClassName().equalsIgnoreCase(Map.class.getName())) {
                 *                  continue;
                 *          }*/
                if (!e.isKeyOfMap())
                {
                    if (e is TemplateSerial)
                    {
                        if (((TemplateSerial)e).getRef() != null)
                        {
                            valuesIndexesRef.put(iValue_, ((TemplateSerial)e).getRef());
                        }
                    }
                    values.Add(e.getValue());
                    iValue_++;
                }
                else
                {
                    if (e is TemplateSerial)
                    {
                        if (((TemplateSerial)e).getRef() != null)
                        {
                            keysIndexesRef.put(iKey_, ((TemplateSerial)e).getRef());
                        }
                    }
                    keys.Add(e.getValue());
                    iKey_++;
                }
            }
            foreach (ElementsSerial e in _elt)
            {
                if (e is ComparatorSerial)
                {
                    continue;
                }
                Type   t_        = typeof(IEnumerable);
                string fullType_ = Constants.getTypeFullString(t_);
                if (fullType_.ToLower().Equals(e.getClassName().ToLower()))
                {
                    continue;
                }
                t_        = typeof(ListableKey);
                fullType_ = Constants.getTypeFullString(t_);
                if (fullType_.ToLower().Equals(e.getClassName().ToLower()))
                {
                    continue;
                }

                /*if (e.getClassName().equalsIgnoreCase(List.class.getName())) {
                 *                  continue;
                 *          }
                 *          if (e.getClassName().equalsIgnoreCase(Map.class.getName())) {
                 *                  continue;
                 *          }*/
                string str_ = e.getClassName();
                Type   class_;
                if (str_.Contains(SPECIAL_SEP))
                {
                    string types_ = str_.Substring(str_.IndexOf(SPECIAL_SEP));
                    class_ = Constants.classForName(str_, types_);
                }
                else
                {
                    class_ = Constants.classForName(str_);
                }
                if (!class_.IsInstanceOfType(value))
                {
                    continue;
                }
                //FieldInfo field_ = class_.GetField(e.getField(), BindingFlags.NonPublic |
                //         BindingFlags.Instance);
                FieldInfo field_ = SerializeXmlObject.getField(class_, e.getField());

                /*if (!SerializeXmlObject.isUpdateFinalFields()) {
                 *                  if (Modifier.isFinal(field_.getModifiers())) {
                 *                          continue;
                 *                  }
                 *          }*/
                /*if (Modifier.isStatic(field_.getModifiers())) {
                 *                  continue;
                 *          }*/
                //field_.setAccessible(class_.getAnnotation(RwXml.class)!=null);
                field_.SetValue(value, e.getValue());
            }
        }
Ejemplo n.º 55
0
 public void BugHunt_LengthOfOne()
 {
     l = new MyList();
     l.Add(1);
     Assert.AreEqual(1, l.Length);
 }
Ejemplo n.º 56
0
        private MyList <MyTypeInfo> yamlTypes2CSharpTypes(string swagger_yaml)
        {
            var input = new StringReader(swagger_yaml);

            var yaml = new YamlStream();

            yaml.Load(input);

            var root = (YamlMappingNode)yaml.Documents[0].RootNode;

            var definitions = (YamlMappingNode)root.Children[new YamlScalarNode("definitions")];


            MyList <MyTypeInfo> classes = new MyList <MyTypeInfo>();



            foreach (var entry in definitions.Children)
            {
                MyTypeInfo classdef = new MyTypeInfo(entry.Key.ToString(), "RemoteTypes", new MyTypeInfo(typeof(DatabaseTable)));
                classdef.AddAttribute(new JsonObjectAttribute(MemberSerialization.Fields));
                classes.Add(classdef);
            }

            foreach (var entry in definitions.Children)
            {
                MyTypeInfo classdef = classes.Find(c => c.Name == entry.Key.ToString().Trim());


                var props = (YamlMappingNode)((YamlMappingNode)entry.Value).Children[new YamlScalarNode("properties")];

                int counter = 0;

                foreach (var prop in props.Children)
                {
                    MyTypeInfo fieldtype = null;
                    bool       ismylist  = false;

                    string fieldname = prop.Key.ToString().Trim();

                    Mapping mapping = null;

                    Details details = null;


                    if (((YamlMappingNode)prop.Value).Children.ContainsKey(new YamlScalarNode("$ref")))
                    {
                        string yamlref = ((YamlScalarNode)((YamlMappingNode)prop.Value).Children[new YamlScalarNode("$ref")]).Value;


                        fieldtype = classes.Find(c => c.Name == yamlref.getTextAfterLast("/").Trim());


                        mapping = new Mapping(fieldtype.GetFieldWithAttribute(new ID()).Name);
                    }
                    else
                    {
                        var type = (YamlScalarNode)((YamlMappingNode)prop.Value).Children[new YamlScalarNode("type")];

                        if (type.Value == "array")
                        {
                            var items = (YamlMappingNode)((YamlMappingNode)prop.Value).Children[new YamlScalarNode("items")];


                            if (items.Children.ContainsKey(new YamlScalarNode("$ref")))
                            {
                                string yamlref = ((YamlScalarNode)items.Children[new YamlScalarNode("$ref")]).Value;


                                fieldtype = classes.Find(c => c.Name == yamlref.getTextAfterLast("/"));
                                ismylist  = true;

                                var det_id = new MyFieldInfo(typeof(int), classdef.Name + "_id");
                                det_id.AddAttribute(new Details());
                                fieldtype.AddField(det_id);
                                det_id.AddAttribute(new JsonIgnoreAttribute());

                                details = new Details();
                            }
                            else
                            {
                                var type2 = (YamlScalarNode)items.Children[new YamlScalarNode("type")];


                                ismylist = true;

                                MyTypeInfo  newtable    = new MyTypeInfo(fieldname + "_table", "RemoteTypes", new MyTypeInfo(typeof(DatabaseTable)));
                                MyFieldInfo newtable_id = new MyFieldInfo(typeof(int), fieldname + "_id");
                                newtable_id.AddAttribute(new ID());
                                newtable.AddField(newtable_id);

                                MyFieldInfo newtable_ref = new MyFieldInfo(typeof(int), classdef.Name + "_id");
                                newtable.AddField(newtable_ref);
                                newtable_ref.AddAttribute(new Details());
                                newtable_ref.AddAttribute(new Mapping(classdef.GetFieldWithAttribute(new ID()).Name));


                                MyFieldInfo newtable_value = new MyFieldInfo(swaggerType2CSharpType(type2.Value), fieldname);
                                newtable.AddField(newtable_value);

                                classes.Add(newtable);

                                fieldtype = newtable;
                            }
                        }
                        else
                        {
                            fieldtype = new MyTypeInfo(swaggerType2CSharpType(type.Value));
                        }
                    }



                    MyFieldInfo fi = new MyFieldInfo(fieldtype, fieldname, ismylist);
                    counter++;

                    if (counter == 1)
                    {
                        fi.AddAttribute(new ID());
                    }

                    if (fieldtype.internalType != null && fieldtype.internalType.Equals(typeof(string)))
                    {
                        fi.AddAttribute(new NullableString());
                    }

                    if (mapping != null)
                    {
                        fi.AddAttribute(mapping);
                    }

                    if (details != null)
                    {
                        fi.AddAttribute(details);
                    }


                    classdef.AddField(fi);
                }
            }



            return(classes);
        }