Example #1
0
    public static void Main () {
        // test #1: casting of IEnumerable containg doubles to IEnumerable<double> should work
        var list = new ArrayList() { 1.23, 4.56, 7.89 };
        PrintDoubles(list.Cast<double>());

        // test #2: an exception should be thrown once the string element is reached
        list.Add("foo");
        try {
            PrintDoubles(list.Cast<double>());
            Console.WriteLine("Fail");
        } catch (InvalidCastException) {
            Console.WriteLine("Pass");
        }
    }
Example #2
0
        //ofType,Cast,AsEnumerable,AsQuerable
        public static void Exm9()
        {
            ArrayList cll = new ArrayList();

            cll.AddRange(new int[] { 3, 4, 5 });
            IEnumerable <int> seq1 = cll.Cast <int>();   // кастит только в заданный тип
            IEnumerable <int> seq2 = cll.OfType <int>(); //выбирать только  заданный тип
        }
Example #3
0
        /// <summary>
        /// Handles actuation of a button representing an alphanumeric character
        /// </summary>
        public void HandleAlphaNumericChar(ArrayList modifiers, char inputChar)
        {
            Context.AppAgentMgr.Keyboard.Send((modifiers != null) ? modifiers.Cast <Keys>().ToList() : KeyStateTracker.GetExtendedKeys(), inputChar);

            KeyStateTracker.KeyTriggered(inputChar);

            _lastAction = LastAction.AlphaNumeric;
        }
        /// <summary>
        /// Retrieves the type objects for all subclasses of the given type within the loaded plugins.
        /// </summary>
        /// <param name="baseClass">The base class</param>
        /// <returns>All subclases</returns>
        public string[] GetSubclasses(string baseClass)
        {
            Type baseClassType = Type.GetType(baseClass) ?? GetTypeByName(baseClass);

            if (baseClassType == null)
            {
                throw new ArgumentException("Cannot find a type of name " + baseClass +
                                            " within the plugins or the common library.");
            }
            var subclassList = new ArrayList();

            foreach (var pluginType in TypeList.Cast <Type>().Where(pluginType => pluginType.IsSubclassOf(baseClassType)))
            {
                subclassList.Add(pluginType.FullName);
            }
            return((string[])subclassList.ToArray(typeof(string)));
        }
Example #5
0
        public void Should_cast_arraylist_to_enumerable()
        {
            ArrayList names = GetNames();

            var result = names.Cast <string>();

            Check.That(result.Count()).IsEqualTo(names.Count);
        }
Example #6
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Gets hash table. </summary>
        ///
        /// <remarks>   Jaege, 17/09/2018. </remarks>
        ///
        /// <param name="hashTable">    The hash table. </param>
        /// <param name="array">        The array. </param>
        ///-------------------------------------------------------------------------------------------------

        public void GetHashTable(Hashtable hashTable, ArrayList array)
        {
            QuestionsArrayList Questions = new QuestionsArrayList(questionNo1, questionOperator, questionNo2, questionEquals, questionAnswer);
            var cast = array.Cast <QuestionsArrayList>().ToDictionary(item => item.questionNo1 + item.questionOperator +
                                                                      item.questionNo2 + item.questionEquals + item.questionAnswer);

            hashTable = new Hashtable(cast);
        }
        public List <dataRecord> querySelection(string url)
        {
            HtmlWeb web = new HtmlWeb();

            HtmlAgilityPack.HtmlDocument document = web.Load(url);
            HtmlNode[] nodeNames = document.DocumentNode.SelectNodes("//div[@class='box-list-job']//ul//li[contains(@class, 'jsx-896248193')]//a[@href]").ToArray();

            ArrayList arr = new ArrayList();

            HtmlNode[] nodeSalary = document.DocumentNode.SelectNodes("//div[@class='box-list-job']//div[@title='Mức lương']").ToArray();
            HtmlNode[] nodeDate   = document.DocumentNode.SelectNodes("//div[@class='box-list-job']//div[@title='Hạn nộp hồ sơ']").ToArray();

            HtmlNode[] nodeCountry = document.DocumentNode.SelectNodes("//div[@class='box-list-job']//div[@class='jsx-896248193 job-desc truncate-ellipsis text-center']").ToArray();


            foreach (HtmlNode link in document.DocumentNode.SelectNodes("//div[@class='jsx-896248193 job-ttl truncate-ellipsis']//a[@href]"))
            {
                HtmlAttribute att = link.Attributes["href"];
                string        a   = att.Value;
                arr.Add(a);
            }

            ArrayList arrayRecord = new ArrayList();

            for (int i = 0; i < arr.Count; i++)
            {
                string href        = "https://vieclam24h.vn" + arr[i].ToString();
                string salary      = nodeSalary[i].InnerText.ToString();
                string name        = "";
                string nameCompany = "";
                string country     = "";
                string date        = nodeDate[i].InnerText.ToString();
                if (i == 0)
                {
                    name        = nodeNames[i].InnerText;
                    nameCompany = nodeNames[i + 1].InnerText;
                }
                else
                {
                    name        = nodeNames[i * 2].InnerText;
                    nameCompany = nodeNames[i * 2 + 1].InnerText;
                }
                if (i == 0)
                {
                    country = nodeCountry[1].InnerText.ToString();
                }
                else
                {
                    country = nodeCountry[i * 3 + 1].InnerText.ToString();
                }

                arrayRecord.Add(new Web_Tim_Viec.Models.dataRecord(href, name, nameCompany, salary, country, date));
            }

            List <dataRecord> list = arrayRecord.Cast <dataRecord>().ToList();

            return(list);
        }
Example #8
0
        /* My algorithm was to re-arrange the array to the largest qty first (As assumed that a higher qty
         * had a lower price) so that if a higher qty of a product fit into the users qty total. The loop will
         * then iterate through each pack qty and if it matched it will break out of the loop
         */
        public int[] calc(int items)
        {
            int qty;

            int[] temp = new int[list.Count];

            int count = list.Count;


            foreach (var k in list)
            {
                int num = k.Key;
                temp[count - 1] = num;
                count--;
            }


            //boolean to break out of loop when a match has been found
            bool      success     = false;
            ArrayList resultStack = new ArrayList();

            int startPos = 0;

            do
            {
                //create 2 variables. one for starting position and one for iterating
                //empty list and start from second
                qty = items;
                resultStack.Clear();
                int x = startPos;

                for (; x < temp.Length; x++)
                {
                    while ((qty - temp[x]) >= 0)
                    {
                        qty = qty - temp[x];
                        resultStack.Add(temp[x]);
                        if (qty == 0)
                        {
                            success = true;
                            break;
                        }
                    }
                }

                if (startPos == (temp.Length - 1))
                {
                    Console.WriteLine("Nothing Found");
                    break;
                }
                startPos++;
            } while (success == false);

            int[] results = resultStack.Cast <int>().ToArray();

            return(results);
        }
Example #9
0
        static void Main(string[] args)
        {
            string[] greetings = { "hello world", "hello LINQ", "hello Apress" };
            var      output    = from s in greetings
                                 where s.EndsWith("LINQ")
                                 select s;

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

            //Converting an array of strings to Integers and sorting it
            string[] numbers = { "7", "9", "11", "25", "10", "45" };
            var      nums    = numbers.Select(s => Int32.Parse(s)).OrderBy(s => s).ToArray();

            foreach (var num in nums)
            {
                Console.WriteLine(num);
            }

            //Convertng a Legacy collection into an IEnumerable<T> using Cast operator
            ArrayList arraylist = new ArrayList();

            arraylist.Add("JeevanTha");
            arraylist.Add("Jeevan");
            arraylist.Add("outstanding");
            arraylist.Add("program");

            IEnumerable <string> str = arraylist.Cast <string>() //using cast
                                       .Where(n => n.Length < 7);

            foreach (string st in str)
            {
                Console.WriteLine(st);
            }

            //Convertng a Legacy collection into an IEnumerable<T> using OFType operator
            IEnumerable <string> names = arraylist.OfType <string>().Where(n => n.Length > 7);

            foreach (string name in names)
            {
                Console.WriteLine(name);
            }

            //Query with intentional Exception Deferred until Enumeration
            string[] strings = { "one", "two", "null", "three" };
            Console.WriteLine("before where() is called");
            IEnumerable <string> ieStrings = strings.Where(s => s.Length == 3);

            Console.WriteLine("After where() is called");
            foreach (string s in ieStrings)
            {
                Console.WriteLine("Processing " + s);
            }
            Console.ReadLine();
        }
Example #10
0
 public void Salvaraqr()
 {
     Console.Clear();
     File.WriteAllLines(@pathFile, elementos.Cast <string>());
     Console.WriteLine("Arquivo atualizo com sucesso");
     Console.Write("Pressione qualquer tecla para voltar pro menu principal...");
     Console.ReadKey();
     menu();
 }
Example #11
0
        List <SearchVenue> PushVenue(SearchVenue cardModel, List <SearchVenue> dayByDayList, int position)
        {
            ArrayList arrayList = new ArrayList(dayByDayList);

            arrayList.Insert(Convert.ToInt16(position), cardModel);
            var currentDayList = arrayList.Cast <SearchVenue>().ToList();

            return(currentDayList);
        }
        public void CollectionInitEmpty()
        {
            var testCollection        = new ArrayList();
            var testCollection1       = new[] { "element2", "element3" };
            var testCollectionFacet   = new CollectionFacet(specification);
            var testAdaptedCollection = AdapterFor(testCollection);

            Init(testCollectionFacet, testAdaptedCollection, testCollection.Cast <object>(), testCollection1);
        }
        public void CollectionInitAllEmpty()
        {
            var testCollection        = new ArrayList();
            var testCollection1       = new string[] { };
            var testCollectionFacet   = new CollectionFacet(specification);
            var testAdaptedCollection = AdapterFor(testCollection);

            Init(testCollectionFacet, testAdaptedCollection, testCollection.Cast <object>(), testCollection1);
        }
Example #14
0
        private List <IntPtr> GetWindows()
        {
            ArrayList WindowHandles = new ArrayList();

            EnumedWindow callBackPtr = GetWindowHandle;

            EnumWindows(callBackPtr, WindowHandles);
            return(WindowHandles.Cast <IntPtr>().ToList());
        }
Example #15
0
        ///<summary>
        ///Construct the palette quantizer.
        ///</summary>
        ///<param name="palette">The color palette to quantize to.</param>
        ///<remarks>
        ///This quantization method only requires a single quantization step when a palette is provided.
        ///</remarks>
        public PaletteQuantizer(ArrayList palette = null) : base(palette != null)
        {
            if (palette == null)
            {
                return;
            }

            Colors = new List <Color>(palette.Cast <Color>());
        }
Example #16
0
    public static Vector Create(ArrayList v)
    {
        if (v.Count != v.OfType <Algebraic>().Count())
        {
            throw new JasymcaException("Error creating Vektor.");
        }

        return(new Vector(v.Cast <Algebraic>().ToArray()));
    }
Example #17
0
        public async Task <User> Authenticate(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            var userVerify = await _userManager.FindByNameAsync(userName);

            // check if UserName exists
            if (userVerify == null)
            {
                return(null);
            }


            var user =
                _userManager.PasswordHasher.VerifyHashedPassword(userVerify, userVerify.PasswordHash, password) ==
                PasswordVerificationResult.Success
                    ? userVerify
                    : null;

            // return null if user not found
            if (user == null)
            {
                return(null);
            }


            var roles = await _userManager.GetRolesAsync(user);

            var arrayClaims = new ArrayList {
                new Claim(ClaimTypes.Name, user.Id)
            };

            foreach (var role in roles)
            {
                arrayClaims.Add(new Claim(ClaimTypes.Role, role));
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity((IEnumerable <Claim>)arrayClaims.Cast <Claim>().GetEnumerator()),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);

            return(user);
        }
        public void Test03()
        {
            ArrayList list = new ArrayList {
                "First", "Second", "Third"
            };
            IEnumerable <string> li = list.Cast <string>();

            li.ToList().ForEach(p => Console.WriteLine(p));
            Console.WriteLine("-------------------");
        }
Example #19
0
        public static IEnumerable <Window> EnumWindows()
        {
            var windowHandles = new ArrayList();

            EnumedWindow callBackPtr = GetWindowHandle;

            EnumWindows(callBackPtr, windowHandles);

            return(windowHandles.Cast <IntPtr>().Select(i => new Window(i)));
        }
Example #20
0
        /// <summary>
        /// 標準のソートルール,IDで比較(IComparableが使われる)を確認
        /// </summary>
        /// <param name="objStudents"></param>
        private void SortObjStudents(ArrayList objStudents)
        {
            // 標準のソートルール,IDで比較(IComparableが使われる)
            // StudentにIComparableを実装していないとSort()のタイミングでSystem.InvalidOperationExceptionが出る
            objStudents.Sort();
            var ret = objStudents.Cast <Student>();

            Console.WriteLine(nameof(SortObjStudents));
            WriteSortResult(ret);
        }
Example #21
0
        static void ConvertingDataTypes()
        {
            var list = new ArrayList();

            list.Add(1);
            list.Add(2);
            list.Add(3);

            Console.WriteLine(list.Cast <int>().Average()); // designed for weakly typed collections
        }
Example #22
0
        private void orderByZScore()                                                                                  // Method to sort the Result List by Z-Score in ascending order
        {
            sortedList = new ArrayList();                                                                             // Initialize the arraylist
            var list = resultList.Cast <JObject>().OrderBy(item => Double.Parse(item.GetValue("zScore").ToString())); // sort by Z-Score

            foreach (JObject jObject in list)
            {
                sortedList.Add(jObject);
            }
        }
        void BindSortSettings(ArrayList objSortColumns)
        {
            SaveSortColumnSettings(objSortColumns);
            grdSortColumns.DataSource = objSortColumns.Cast <IDocumentsSortColumn> ()
                                        .Select(sc => new DocumentSortColumnViewModel(sc, ViewModelContext));
            grdSortColumns.DataKeyField = "ColumnName";

            Localization.LocalizeDataGrid(ref grdSortColumns, LocalResourceFile);
            grdSortColumns.DataBind();
        }
        // GET: SqlDetachDemo
        public ActionResult Index(int id = -1)
        {
            ArrayList whereParams = new ArrayList();

            whereParams.Add(new WhereClauseSchema("Id", 1));
            this.SqlDetach.MvcActionResultEvent += SqlDetach_QueryFirstDemo;
            bll.QueryFirst(this.SqlDetach, whereParams.Cast <WhereClauseSchema>().ToArray());

            return(View());
        }
        public static void SauvegarderT1()
        {
            ArrayList list = new ArrayList();

            foreach (Huile huile in T1)
            {
                list.Add(huile.ToString());
            }
            File.WriteAllLines(@"Huiles.txt", list.Cast <string>());
        }
Example #26
0
        public JsonObject[] ToArray()
        {
            ArrayList element = (ArrayList)this.Element;

            if (func_0 == null)
            {
                func_0 = new Func <object, JsonObject>(JsonObject.smethod_0);
            }
            return(Enumerable.Select <object, JsonObject>(element.Cast <object>(), func_0).ToArray <JsonObject>());
        }
Example #27
0
        public IEnumerable <WindowInfo> GetWindows()
        {
            var windowHandles = new ArrayList();

            EnumWindows(GetWindowHandle, windowHandles);

            return(windowHandles.Cast <WindowInfo>()
                   .Where(i => !string.IsNullOrWhiteSpace(i.Description))
                   .ToList());
        }
Example #28
0
    public static void Main()
    {
        // test #1: casting of IEnumerable containg doubles to IEnumerable<double> should work
        var list = new ArrayList()
        {
            1.23, 4.56, 7.89
        };

        PrintDoubles(list.Cast <double>());

        // test #2: an exception should be thrown once the string element is reached
        list.Add("foo");
        try {
            PrintDoubles(list.Cast <double>());
            Console.WriteLine("Fail");
        } catch (InvalidCastException) {
            Console.WriteLine("Pass");
        }
    }
Example #29
0
        public void TestAdapter()
        {
            var a = new ArrayList {
                1, 5, 3, 3, 2, 4, 3
            };
            var sortedA = a.Cast <int>().OrderBy(i => i).ToList();

            a.Sort(new ComparisonAdapter <int>(IntComparer));
            CollectionAssert.AreEqual(sortedA, a);
        }
        public void CollectionGetEnumeratorFor()
        {
            var testCollection = new ArrayList {
                "element1", "element2"
            };
            var testCollectionFacet   = new CollectionFacet(specification);
            var testAdaptedCollection = AdapterFor(testCollection);

            ValidateCollection(testCollectionFacet, testAdaptedCollection, testCollection.Cast <object>());
        }
Example #31
0
        /// <summary>
        /// Retrieves an array of ShellItem objects for sub-folders of this shell item.
        /// </summary>
        /// <returns>ArrayList of ShellItem objects.</returns>
        public List <ShellItem> GetSubFolders()
        {
            // Make sure we have a folder.
            if (IsFolder == false)
            {
                throw new Exception("Unable to retrieve sub-folders for a non-folder.");
            }
            ArrayList arrChildren = new ArrayList();

            try
            {
                // Get the IEnumIDList interface pointer.
                ShellAPI.IEnumIDList pEnum = null;
                uint hRes = ShellFolder.EnumObjects(IntPtr.Zero, ShellAPI.SHCONTF.SHCONTF_FOLDERS, out pEnum);
                if (hRes != 0)
                {
                    Marshal.ThrowExceptionForHR((int)hRes);
                }

                IntPtr pIDL = IntPtr.Zero;
                Int32  iGot = 0;

                // Grab the first enumeration.
                pEnum.Next(1, out pIDL, out iGot);

                // Then continue with all the rest.
                while (!pIDL.Equals(IntPtr.Zero) && iGot == 1)
                {
                    // Create the new ShellItem object.
                    arrChildren.Add(new ShellItem(m_shRootShell, pIDL, this));

                    // Free the PIDL and reset counters.
                    Marshal.FreeCoTaskMem(pIDL);
                    pIDL = IntPtr.Zero;
                    iGot = 0;

                    // Grab the next item.
                    pEnum.Next(1, out pIDL, out iGot);
                }

                // Free the interface pointer.
                if (pEnum != null)
                {
                    Marshal.ReleaseComObject(pEnum);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error:", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }
            var list = new List <ShellItem>(arrChildren.Count);

            list.AddRange(arrChildren.Cast <ShellItem>());
            return(list);
        }
Example #32
0
	public static bool sequenceJustOccured(ArrayList sequence, PlayerController player) {

		if (sequence.Count > player.danceMoves.Count) {
			return false;
		}

		ArrayList relevantMoves = player.danceMoves.GetRange(player.danceMoves.Count - sequence.Count, sequence.Count);
		if (relevantMoves.Cast<object>().SequenceEqual(sequence.Cast<object>())) {
			return true;
		}
		return false;
	}