public static void Main() { ArrayList myArrayList = new ArrayList(); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); string[] anotherStringArray = { "Here's", "some", "more", "text" }; myArrayList.SetRange(0, anotherStringArray); if (myArrayList.Contains("text")) { int index = myArrayList.IndexOf("text"); Console.WriteLine("myArrayList does contain the word 'text'"); Console.WriteLine("'text' first occurs at index " + index); index = myArrayList.LastIndexOf("text"); Console.WriteLine("'text' last occurs at index " + index); } }
// ArrayList alist = new ArrayList(); static void Main(string[] args) { ArrayList al = new ArrayList() { "aleena", "anand", "adarsh" }; foreach (string a in al) { Console.WriteLine(a); } Console.WriteLine(); al.Sort(); foreach (string a in al) { Console.WriteLine(a); } Console.WriteLine(); al.Add("lovely"); foreach (string a in al) { Console.WriteLine(a); } Console.WriteLine(); al.Insert(4, "johnson"); foreach (string a in al) { Console.WriteLine(a); } Console.WriteLine(); al.Reverse(); foreach (string a in al) { Console.WriteLine(a); } string[] r = new string[] { " cat", "mat" }; al.SetRange(1, r); Console.WriteLine(); foreach (string a in al) { Console.WriteLine(a); } Console.WriteLine(); al.RemoveRange(2, 2); Console.WriteLine(); foreach (string a in al) { Console.WriteLine(a); } Console.WriteLine(); }
public static void Main() { ArrayList myArrayList = new ArrayList(); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); string[] anotherStringArray = { "Here's", "some", "more", "text" }; myArrayList.SetRange(0, anotherStringArray); myArrayList.RemoveAt(0); myArrayList.Remove("text"); myArrayList.RemoveRange(3, 2); DisplayArrayList("myArrayList", myArrayList); }
public static void Main() { ArrayList myArrayList = new ArrayList(); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); string[] anotherStringArray = { "Here's", "some", "more", "text" }; myArrayList.SetRange(0, anotherStringArray); Console.WriteLine("Using the GetEnumerator() method to get an enumerator"); IEnumerator myEnumerator = myArrayList.GetEnumerator(); while (myEnumerator.MoveNext()) { Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current); } myEnumerator.Reset(); myEnumerator.MoveNext(); Console.WriteLine("myEnumerator.Current = " + myEnumerator.Current); }
static void UpdateOperation(ArrayList list) { //1.通过下标来修改元素 list[2] = false; //2.批量修改元素 list.SetRange(0, new string[] { "a", "b", "c", "d" }); }
public Element?[] Spell(string word, SearchAlgorithm algorithm) { Dictionary <int, Element> indexed = new Dictionary <int, Element>(); word = Regex.Replace(word.ToLower(), "[^a-z\\s]", ""); switch (algorithm) { case SearchAlgorithm.ElementBased: foreach (Element element in elements) { string symbol = element.Symbol.ToLower(); if (word.Contains(symbol)) { foreach (int i in word.IndexOfAll(symbol)) { indexed.Add(i, element); } word = word.Replace(symbol, new string ('_', symbol.Length)); } } break; case SearchAlgorithm.ChunkSearch: int maxElementLength = elements.Max(e => e.Symbol.Length); for (int searchLength = maxElementLength; searchLength > 0; searchLength--) { Element[] currentElements = elements.Where(e => e.Symbol.Length == searchLength).ToArray(); for (int x = 0; x < word.Length - searchLength + 1; x++) { foreach (Element currentElement in currentElements) { if (word.Substring(x, searchLength) == currentElement.Symbol.ToLower()) { indexed.Add(x, currentElement); ArrayList tmpList = new ArrayList(((ICollection)(Array)word.ToCharArray())); tmpList.SetRange(x, (ICollection)(Array) new string('_', searchLength).ToCharArray()); word = new string(Array.ConvertAll(tmpList.ToArray(), item => (char)item)); } } } } break; } List <Element?> spelled = new List <Element?>(); int max = indexed.Max(item => item.Key); Element value; for (int i = 0; i <= max; i++) { if (indexed.TryGetValue(i, out value)) { spelled.Add(value); } else if (word[i] == ' ') { spelled.Add(null); } } return(spelled.ToArray()); }
private static void Arralist() { ArrayList a1 = new ArrayList() { "Rohitha", "akhila", "vignitha", "padmapriya" }; a1.Sort(); foreach (string a in a1) { Console.WriteLine(a); } Console.WriteLine(); a1.Add("akhila B"); foreach (string a in a1) { Console.WriteLine(a); } Console.WriteLine(); string[] r = new string[] { "cat", "dog" }; a1.SetRange(2, r); foreach (string a in a1) { Console.WriteLine(a); } Console.WriteLine(); a1.Remove("cat"); foreach (string a in a1) { Console.WriteLine(a); } }
static void Main(string[] args) { ArrayList array = new ArrayList() { 1, 2, 3, 4, 5, 6 }; ArrayList tmp = new ArrayList(); int sum = 0; for (int i = 0; i < array.Count; i++) { sum += (int)array[i]; if ((int)array[i] % 2 == 0) // { tmp.Add(array[i]); // четные } } array.Clear(); array.SetRange(0, tmp); foreach (var item in array) { if ((int)item > sum / array.Count) // Элементы больше среднеарифметического { Console.WriteLine(item); } } Console.ReadLine(); }
ArrayList optimizeGesture(ArrayList pointArray) { // take all the points in the gesture and finds the correct points compared with distance and the maximun value of points // calc the interval relative the length of the gesture drawn by the user float interval = calcTotalGestureLength(pointArray) / (maxPoints - 1); // use the same starting point in the new array from the old one. ArrayList optimizedPoints = new ArrayList(); optimizedPoints.Add(pointArray[0]); float tempDistance = 0.0f; // run through the gesture array. Start at i = 1 because we compare point two with point one) for (int i = 1; i < pointArray.Count; ++i) { float currentDistanceBetween2Points = calcDistance((Vector2)pointArray[i - 1], (Vector2)pointArray[i]); if ((tempDistance + currentDistanceBetween2Points) >= interval) { Vector2 v1 = (Vector2)pointArray[i - 1]; Vector2 v = (Vector2)pointArray[i]; // the calc is: old pixel + the differens of old and new pixel multiply float newX = v1.x + ((interval - tempDistance) / currentDistanceBetween2Points) * (v.x - v1.x); float newY = v1.y + ((interval - tempDistance) / currentDistanceBetween2Points) * (v.y - v1.y); // create new point Vector2 newPoint = new Vector2(newX, newY); // set new point into array optimizedPoints.Add(newPoint); ArrayList temp = pointArray.GetRange(i, pointArray.Count - i - 1); Vector2 last = (Vector2)pointArray[pointArray.Count - 1]; pointArray.SetRange(i + 1, temp); pointArray.Add(last); //pointArray.InsertRange(i + 1, temp); pointArray.Insert(i, newPoint); tempDistance = 0.0f; } else { // the point was too close to the last point compared with the interval,. Therefore the distance will be stored for the next point to be compared. tempDistance += currentDistanceBetween2Points; } } // Rounding-errors might happens. Just to check if all the points are in the new array if (optimizedPoints.Count == maxPoints - 1) { Vector2 v = (Vector2)pointArray[pointArray.Count - 1]; optimizedPoints.Add(new Vector2(v.x, v.y)); } return(optimizedPoints); }
static int SetRange(IntPtr L) { LuaScriptMgr.CheckArgsCount(L, 3); ArrayList obj = (ArrayList)LuaScriptMgr.GetNetObjectSelf(L, 1, "ArrayList"); int arg0 = (int)LuaScriptMgr.GetNumber(L, 2); ICollection arg1 = (ICollection)LuaScriptMgr.GetNetObject(L, 3, typeof(ICollection)); obj.SetRange(arg0, arg1); return(0); }
static void Main(string[] args) { //arraylist(); Hashtable hst = new Hashtable(); hst.Add("raju", 12345); hst.Add("karan", 5678); hst.Add("rjun", 6789); foreach (string k in hst.Values) { Console.WriteLine(k); } hst.Remove("karan"); ArrayList al = new ArrayList() { "goku", "gohan", "gotan", "pikalu", "vigeta" }; foreach (string a in al) { Console.WriteLine(a); } al.Sort(); foreach (string a in al) { Console.WriteLine(a); } al.Add("freeza"); al.Add("cell"); al.Insert(4, "kick bu"); foreach (string a in al) { Console.WriteLine(a); } al.Reverse(); foreach (string a in al) { Console.WriteLine(a); } string[] r = new string[] { "cat", "mat" }; al.SetRange(4, r); foreach (string a in al) { Console.WriteLine(a); } al.RemoveRange(2, 2); Console.WriteLine(); foreach (string a in al) { Console.WriteLine(a); } }
static void Main(string[] args) { //arraylist(); Hashtable hst = new Hashtable(); hst.Add("raju", 12345); hst.Add("karan", 5678); hst.Add("arjun", 6789); foreach (string k in hst.Values) { Console.WriteLine(k); } hst.Remove("karan"); ArrayList al = new ArrayList() { "teja", "ambi", "vishnu", "siri" }; foreach (string a in al) { Console.WriteLine(a); } al.Sort(); foreach (string a in al) { Console.WriteLine(a); } al.Add("akhil"); al.Add("shri"); al.Insert(4, "siva"); foreach (string a in al) { Console.WriteLine(a); } al.Reverse(); foreach (string a in al) { Console.WriteLine(a); } string[] r = new string[] { "cat", "mat" }; al.SetRange(4, r); foreach (string a in al) { Console.WriteLine(a); } al.RemoveRange(2, 2); Console.WriteLine(); foreach (string a in al) { Console.WriteLine(a); } }
static void Main(string[] args) { Console.WriteLine("Creating and Adding Elements into ArrayList:\n"); ArrayList al = new ArrayList() { "Kaviraj", "Damodar", "Deepak", "Saurabh" }; al.Add("Rathod"); al.Add("Pune"); foreach (string i in al) { Console.WriteLine(i); } Console.WriteLine("\nReverse ArrayList\n"); al.Reverse(); foreach (string i in al) { Console.WriteLine(i); } Console.WriteLine("\nInsert Elements at Specified Location\n"); al.Insert(5, "Kavi"); foreach (string i in al) { Console.WriteLine(i); } Console.WriteLine("\nSetRange\n"); string[] str = new string[] { "Latur", "Buldhana", "Nagar" }; al.SetRange(4, str); foreach (string a in al) { Console.WriteLine(a); } Console.ReadKey(); }
static void Main(string[] args) { ArrayList al = new ArrayList() { "Ambica", "teju", "vishnu", "sree", "Anu", "dil" }; foreach (string a in al) { Console.WriteLine(a); } al.Sort(); foreach (string a in al) { Console.WriteLine(a); } al.Add("Bharat"); al.Add("kalyani"); al.Insert(4, "Hrithik"); foreach (string a in al) { Console.WriteLine(a); } al.Reverse(); foreach (string a in al) { Console.WriteLine(a); } string[] r = new string[] { "cat", "rat" }; al.SetRange(4, r); foreach (string a in al) { Console.WriteLine(a); } al.RemoveRange(2, 2); Console.WriteLine(); foreach (string a in al) { Console.WriteLine(a); } }
public void TestArrayListSetRangeOverflow() { ArrayList arrayList = new ArrayList(); arrayList.Add(this); try { arrayList.SetRange(Int32.MaxValue, new ArrayList()); Fail("Should have thrown an ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException e) { } catch (Exception e) { Fail("Should have thrown an ArgumentOutOfRangeException instead of " + e.GetType().Name); } }
public void SetRange() { int innerIterationCount = (int)Benchmark.InnerIterationCount; int startIndex = 0; int size = 100000; ArrayList elements = CreateArrayList(size); var newElemnts = new ArrayList(size); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < innerIterationCount; i++) { elements.SetRange(startIndex, elements); } } } }
static void Main(string[] args) { ArrayList al = new ArrayList() { "Kaviraj", "Damodar", "Deepak", "Saurabh" }; al.Add("Rathod"); al.Add("Pune"); foreach (string i in al) { Console.WriteLine(i); } al.Reverse(); foreach (string i in al) { Console.WriteLine(i); } al.Insert(5, "Kavi"); foreach (string i in al) { Console.WriteLine(i); } string[] str = new string[] { "Latur", "Buldhana", "Nagar" }; al.SetRange(4, str); foreach (string a in al) { Console.WriteLine(a); } Console.ReadKey(); }
private static void ArrayListObj() { ArrayList al = new ArrayList() { "dp", "prasad", "vishnu", "momu", "rohit" }; foreach (string a in al) { Console.WriteLine(a); } al.Add("anil"); foreach (string a in al) { Console.WriteLine(a); } al.Sort(); foreach (string a in al) { Console.WriteLine(a); } al.Insert(2, "dillep"); foreach (string a in al) { Console.WriteLine(a); } string[] r = new string[] { "car", "bike" }; al.SetRange(2, r); foreach (string a in al) { Console.WriteLine(a); } al.Reverse(); foreach (string a in al) { Console.WriteLine(a); } }
public static void Main() { ArrayList myArrayList = new ArrayList(); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); myArrayList.Add("A"); string[] anotherStringArray = { "Here's", "some", "more", "text" }; myArrayList.SetRange(0, anotherStringArray); ArrayList anotherArrayList = myArrayList.GetRange(1, 2); DisplayArrayList("anotherArrayList", anotherArrayList); }
public static void Main() { // Creates and initializes a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add("The"); myAL.Add("quick"); myAL.Add("brown"); myAL.Add("fox"); myAL.Add("jumps"); myAL.Add("over"); myAL.Add("the"); myAL.Add("lazy"); myAL.Add("dog"); // Creates and initializes the source ICollection. Queue mySourceList = new Queue(); mySourceList.Enqueue("big"); mySourceList.Enqueue("gray"); mySourceList.Enqueue("wolf"); // Displays the values of five elements starting at index 0. ArrayList mySubAL = myAL.GetRange(0, 5); Console.WriteLine("Index 0 through 4 contains:"); PrintValues(mySubAL, '\t'); // Replaces the values of five elements starting at index 1 with the values in the ICollection. myAL.SetRange(1, mySourceList); // Displays the values of five elements starting at index 0. mySubAL = myAL.GetRange(0, 5); Console.WriteLine("Index 0 through 4 now contains:"); PrintValues(mySubAL, '\t'); }
static void Main(string[] args) { var a = new ArrayList(); a.Add(234); a.Add(234); a.Add(4444444); a.Add(234); a.Add(2341234); a.RemoveAt(0); a.Remove(4444444); Display(a); a[0] = DateTime.Now.AddMonths(-1); Display(a); int count = a.Count; int idx = a.IndexOf(234); a.Insert(2, 999999); Display(a); bool b = a.Contains(999999); a.Reverse(0, a.Count); Display(a); var mas = a.ToArray(); a.SetRange(0, new [] { 1, 3, 2, 3 }); Display(a); var s = new Stack(); s.Push(22); s.Push(33); s.Push(44); Display(s); var x = s.Pop(); Display(s); var q = new Queue(); q.Enqueue(111); q.Enqueue(222); q.Enqueue(333); Display(q); var e = q.Dequeue(); Display(q); }
public void TestSetRange() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; ArrayList arrSetRange = null; int start = 3; string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Wildcat", "Wonder Woman", };//22 string[] strSetRange = { "Hardware", "Icon", "Johnny Quest", "Captain Sisko", "Captain Picard", "Captain Kirk", "Agent J", "Agent K", "Space Ghost", "Wolverine", "Cyclops", "Storm", "Lone Ranger", "Tonto", "Supergirl", };//15 // Construct ArrayList. arrList = new ArrayList((ICollection)strHeroes); arrSetRange = new ArrayList((ICollection)strSetRange); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)ArrayList.FixedSize(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone()}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // SetRange entire array list. arrList.SetRange(start, arrSetRange); // Verify set. for (int ii = 0; ii < arrSetRange.Count; ++ii) { Assert.Equal(0, ((string)arrList[start + ii]).CompareTo((String)arrSetRange[ii])); } // // [] Attempt invalid SetRange using collection that exceed valid range. // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.SetRange(start, arrList)); // // [] Attempt invalid SetRange using negative index // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.SetRange(-100, arrSetRange)); // // [] Attempt SetRange using out of range index // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.SetRange(1000, arrSetRange)); // // [] Attempt SetRange using null collection. // Assert.Throws<ArgumentNullException>(() => arrList.SetRange(0, null)); } }
public virtual bool runTest() { int iCountErrors = 0; int iCountTestcases = 0; Console.Error.WriteLine(strName + ": " + strTest + " runTest started..."); ArrayList arrList = null; ArrayList arrSetRange = null; int start = 3; String [] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Wildcat", "Wonder Woman", }; String [] strSetRange = { "Hardware", "Icon", "Johnny Quest", "Captain Sisko", "Captain Picard", "Captain Kirk", "Agent J", "Agent K", "Space Ghost", "Wolverine", "Cyclops", "Storm", "Lone Ranger", "Tonto", "Supergirl", }; do { ++iCountTestcases; Console.Error.WriteLine("[] Construct ArrayList"); try { arrList = new ArrayList((ICollection)strHeroes); if (arrList == null) { Console.WriteLine(strTest + "E_101: Failed to construct new ArrayList"); ++iCountErrors; break; } arrSetRange = new ArrayList((ICollection)strSetRange); if (arrSetRange == null) { Console.WriteLine(strTest + "E_102: Failed to construct new ArrayList arrSetRange"); ++iCountErrors; break; } } catch (Exception ex) { Console.WriteLine(strTest + "E_10001: Unexpected Exception: " + ex.ToString()); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine("[] Set range in the array list"); try { arrList.SetRange(start, arrSetRange); for (int ii = 0; ii < arrSetRange.Count; ++ii) { if (((String)arrList[start + ii]).CompareTo((String)arrSetRange[ii]) != 0) { String strInfo = strTest + " error: "; strInfo = strInfo + "Expected hero <" + (String)arrList[start + ii] + "> "; strInfo = strInfo + "Returned hero <" + (String)arrSetRange[ii] + "> "; Console.WriteLine(strTest + "E_202: " + strInfo); ++iCountErrors; break; } } } catch (Exception ex) { Console.WriteLine(strTest + "E_10002: Unexpected Exception: " + ex.ToString()); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine("[] Attempt bogus SetRange using collection that exceed valid range"); try { arrList.SetRange(start, arrList); Console.WriteLine(strTest + "E_303: Expected ArgumentException"); ++iCountErrors; break; } catch (ArgumentException ex) { } catch (Exception ex) { Console.WriteLine(strTest + "E_10003: Unexpected Exception: " + ex.ToString()); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine("[] Attempt bogus SetRange using negative index"); try { arrList.SetRange(-100, arrSetRange); Console.WriteLine(strTest + "E_303: Expected ArgumentException"); ++iCountErrors; break; } catch (ArgumentException ex) { } catch (Exception ex) { Console.WriteLine(strTest + "E_10003: Unexpected Exception: " + ex.ToString()); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine("[] Attempt SetRange using out of range index"); try { arrList[1000] = arrSetRange; Console.WriteLine(strTest + "E_404: Expected ArgumentException"); ++iCountErrors; break; } catch (ArgumentException ex) { } catch (Exception ex) { Console.WriteLine(strTest + "E_10004: Unexpected Exception: " + ex.ToString()); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine("[] Attempt SetRange using null value"); try { arrSetRange.SetRange(0, null); Console.WriteLine(strTest + "E_404: Expected ArgumentException"); ++iCountErrors; break; } catch (ArgumentException ex) { } catch (Exception ex) { Console.WriteLine(strTest + "E_10005: Unexpected Exception: " + ex.ToString()); ++iCountErrors; break; } }while (false); Console.Error.Write(strName); Console.Error.Write(": "); if (iCountErrors == 0) { Console.Error.WriteLine(strTest + " iCountTestcases==" + iCountTestcases + " paSs"); return(true); } else { System.String strFailMsg = null; Console.WriteLine(strTest + strPath); Console.WriteLine(strTest + "FAiL"); Console.Error.WriteLine(strTest + " iCountErrors==" + iCountErrors); return(false); } }
/// <summary> /// Copies the elements of a collection over a range of elements in the list. /// </summary> /// <param name="index">The zero-based index at which to start copying the elements /// of otherList</param> /// <param name="otherList">The other list whose elements to copy to the list.</param> public void SetRange(int index, IntegerList otherList) { list.SetRange(index, otherList.list); }
public virtual bool runTest() { int iCountErrors = 0; int iCountTestcases = 0; Console.Error.WriteLine( strName + ": " + strTest + " runTest started..." ); ArrayList arrList = null; ArrayList arrSetRange = null; int start = 3; String [] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Wildcat", "Wonder Woman", }; String [] strSetRange = { "Hardware", "Icon", "Johnny Quest", "Captain Sisko", "Captain Picard", "Captain Kirk", "Agent J", "Agent K", "Space Ghost", "Wolverine", "Cyclops", "Storm", "Lone Ranger", "Tonto", "Supergirl", }; do { ++iCountTestcases; Console.Error.WriteLine( "[] Construct ArrayList" ); try { arrList = new ArrayList( (ICollection) strHeroes ); if ( arrList == null ) { Console.WriteLine( strTest+ "E_101: Failed to construct new ArrayList" ); ++iCountErrors; break; } arrSetRange = new ArrayList( (ICollection) strSetRange ); if ( arrSetRange == null ) { Console.WriteLine( strTest+ "E_102: Failed to construct new ArrayList arrSetRange" ); ++iCountErrors; break; } } catch (Exception ex) { Console.WriteLine( strTest+ "E_10001: Unexpected Exception: " + ex.ToString() ); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine( "[] Set range in the array list" ); try { arrList.SetRange( start, arrSetRange ); for ( int ii = 0; ii < arrSetRange.Count; ++ii ) { if ( ((String)arrList[start+ii]).CompareTo( (String)arrSetRange[ii] ) != 0 ) { String strInfo = strTest + " error: "; strInfo = strInfo + "Expected hero <" + (String)arrList[start+ii] + "> "; strInfo = strInfo + "Returned hero <"+ (String)arrSetRange[ii] + "> "; Console.WriteLine( strTest+ "E_202: " + strInfo ); ++iCountErrors; break; } } } catch (Exception ex) { Console.WriteLine( strTest+ "E_10002: Unexpected Exception: " + ex.ToString() ); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine( "[] Attempt bogus SetRange using collection that exceed valid range" ); try { arrList.SetRange( start, arrList ); Console.WriteLine( strTest+ "E_303: Expected ArgumentException" ); ++iCountErrors; break; } catch (ArgumentException ex) { } catch (Exception ex) { Console.WriteLine( strTest+ "E_10003: Unexpected Exception: " + ex.ToString() ); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine( "[] Attempt bogus SetRange using negative index" ); try { arrList.SetRange( -100, arrSetRange ); Console.WriteLine( strTest+ "E_303: Expected ArgumentException" ); ++iCountErrors; break; } catch (ArgumentException ex) { } catch (Exception ex) { Console.WriteLine( strTest+ "E_10003: Unexpected Exception: " + ex.ToString() ); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine( "[] Attempt SetRange using out of range index" ); try { arrList[ 1000] = arrSetRange ; Console.WriteLine( strTest+ "E_404: Expected ArgumentException" ); ++iCountErrors; break; } catch (ArgumentException ex) { } catch (Exception ex) { Console.WriteLine( strTest+ "E_10004: Unexpected Exception: " + ex.ToString() ); ++iCountErrors; break; } ++iCountTestcases; Console.Error.WriteLine( "[] Attempt SetRange using null value" ); try { arrSetRange.SetRange( 0, null ); Console.WriteLine( strTest+ "E_404: Expected ArgumentException" ); ++iCountErrors; break; } catch (ArgumentException ex) { } catch (Exception ex) { Console.WriteLine( strTest+ "E_10005: Unexpected Exception: " + ex.ToString() ); ++iCountErrors; break; } } while ( false ); Console.Error.Write( strName ); Console.Error.Write( ": " ); if ( iCountErrors == 0 ) { Console.Error.WriteLine( strTest + " iCountTestcases==" + iCountTestcases + " paSs" ); return true; } else { System.String strFailMsg = null; Console.WriteLine( strTest+ strPath ); Console.WriteLine( strTest+ "FAiL" ); Console.Error.WriteLine( strTest + " iCountErrors==" + iCountErrors ); return false; } }
public new void SetRange(int index, ICollection c) { _List.SetRange(index, c); }
static void Main() { //Un arrayList contine mai multe valori de tipuri diferite //ArrayList-urile nu sunt eficiente ArrayList list = new ArrayList(); Random rnd = new Random(); for (int i = 0; i < 9; i++) { list.Add(rnd.Next() % 100); } ArrayList floats = new ArrayList(new float[] { 1.23f, -2.34f, (float)Math.PI }); list.AddRange(floats); ArrayList chars = new ArrayList(new char[] { 'c', 'd', '.' }); list.AddRange(chars); int integers = 0, reals = 0, letters = 0; for (int i = 0; i < list.Count; i++) { if (list[i] is int) { integers++; } else if (list[i] is char) { letters++; } else if (list[i] is float) { reals++; } } Console.WriteLine("Integers:" + integers); Console.WriteLine("Reals:" + reals); Console.WriteLine("Letters:" + letters); // list.Sort(); <-- Eroare! Valorile nu au tipuri identice // Deci sortarea este imposibila //Implementeaza QuickSort foreach (var s in list) { Console.Write(s + "\t"); } list.Reverse(); Console.WriteLine(); foreach (var s in list) { Console.Write(s + "\t"); } ArrayList bucata = new ArrayList(list.GetRange(2, 2)); Console.WriteLine("\nBucata [2,3] din list :"); foreach (var v in bucata) { Console.Write(v + "\t"); } Console.WriteLine(); list.SetRange(0, new bool[] { true, true, false, false, true }); foreach (var v in list) { Console.Write(v + "\t"); } Console.WriteLine(list.IndexOf(3)); Console.WriteLine(list.LastIndexOf(3)); Console.ReadKey(); return; }
static ArrayList optimizeGesture(ArrayList pointArray, int maxPoints) { // take all the points in the gesture and finds the correct points compared with distance and the maximun value of points // calc the interval relative the length of the gesture drawn by the user float interval = calcTotalGestureLength(pointArray) / (maxPoints - 1); // use the same starting point in the new array from the old one. ArrayList optimizedPoints = new ArrayList(); optimizedPoints.Add(pointArray[0]); float tempDistance = 0.0f; // run through the gesture array. Start at i = 1 because we compare point two with point one) for (int i = 1; i < pointArray.Count; ++i) { float currentDistanceBetween2Points = calcDistance((Vector2)pointArray[i - 1], (Vector2)pointArray[i]); if ((tempDistance + currentDistanceBetween2Points) >= interval) { Vector2 v1 = (Vector2)pointArray[i - 1]; Vector2 v = (Vector2)pointArray[i]; // the calc is: old pixel + the differens of old and new pixel multiply float newX = v1.x + ((interval - tempDistance) / currentDistanceBetween2Points) * (v.x - v1.x); float newY = v1.y + ((interval - tempDistance) / currentDistanceBetween2Points) * (v.y - v1.y); // create new point Vector2 newPoint = new Vector2(newX, newY); // set new point into array optimizedPoints.Add(newPoint); ArrayList temp = pointArray.GetRange(i, pointArray.Count - i - 1); Vector2 last = (Vector2)pointArray[pointArray.Count - 1]; pointArray.SetRange(i + 1, temp); pointArray.Add(last); //pointArray.InsertRange(i + 1, temp); pointArray.Insert(i, newPoint); tempDistance = 0.0f; } else { // the point was too close to the last point compared with the interval,. Therefore the distance will be stored for the next point to be compared. tempDistance += currentDistanceBetween2Points; } } // Rounding-errors might happens. Just to check if all the points are in the new array if (optimizedPoints.Count == maxPoints - 1) { Vector2 v = (Vector2)pointArray[pointArray.Count - 1]; optimizedPoints.Add(new Vector2(v.x, v.y)); } return optimizedPoints; }
public void ArrOutput(ArrayList arrList) { int[] arrInt = new int[3]; ArrShow(arrList, "arrList"); Console.WriteLine("\narrList内的数组元素int[] {{1,2,3}}中的元素[1]输出: \n{0}\n", ((int[])arrList[7])[1]); Console.WriteLine("\narrList的克隆arrListClone: "); arrListClone = (ArrayList)arrList.Clone(); ArrShow(arrListClone, "arrListClone"); Console.WriteLine("\n清空arrListClone: "); arrListClone.Clear(); ArrShow(arrListClone, "arrListClone"); Console.WriteLine("\n将2-4的元素复制到int数组arrInt中: "); arrList.CopyTo(2, arrInt, 0, 3); Console.WriteLine("int数组arrInt内的元素: \n"); foreach (int output in arrInt) { Console.WriteLine(output); } Console.WriteLine("\n查找40所在的位置: "); Console.WriteLine("IndexOf: 角标: {0} ,位置: {1}", arrList.IndexOf(40), arrList.IndexOf(40) + 1); Console.WriteLine("LastIndexOf: 角标: {0} ,位置: {1}", arrList.LastIndexOf(40), arrList.LastIndexOf(40) + 1); Console.WriteLine("BinarySearch: 角标: {0} ,位置: {1}", arrList.BinarySearch(40), arrList.BinarySearch(40) + 1); Console.WriteLine("\n将\"123456\"插入到角标3: "); arrList.Insert(3, 123456); ArrShow(arrList, "arrList"); Console.WriteLine("\n再将角标3的元素移除: "); arrList.RemoveAt(3); ArrShow(arrList, "arrList"); Console.WriteLine("\n将arrList元素的位置反转: "); arrList.Reverse(); ArrShow(arrList, "arrList"); Console.WriteLine("比较arrList和arrListClone是否相等: {0}", arrList.Equals(arrListClone)); arrListClone = (ArrayList)arrList.Clone(); Console.WriteLine("\n将arrList复制给arrListClone再比较: {0}", arrList.Equals(arrListClone)); Console.WriteLine("\n将arrList的最大元素数设置为实际的元素数"); arrList.TrimToSize(); ArrShow(arrList, "arrList"); arrListClone.SetRange(0, arrList); Console.WriteLine("\n比较arrList和arrListClone是否相等: {0}\n", arrList.Equals(arrListClone)); ArrShow(arrList, "arrList"); Console.WriteLine(); ArrShow(arrListClone, "arrListClone"); }
static void Main(string[] args) { //ArrayList tanımlama ArrayList liste = new ArrayList(); Console.WriteLine($"Capacity: {liste.Capacity}"); Console.WriteLine($"Count: {liste.Count}"); //Veri Ekleme liste.Add('a'); Console.WriteLine($"----Güncellem-----"); Console.WriteLine($"Capacity: {liste.Capacity}"); Console.WriteLine($"Count: {liste.Count}"); liste.Add(1); liste.Add(true); liste.Add("aaa"); Console.WriteLine($"----Güncellem-----"); Console.WriteLine($"Capacity: {liste.Capacity}"); Console.WriteLine($"Count: {liste.Count}"); liste.Add("dsds"); Console.WriteLine($"----Güncellem-----"); Console.WriteLine($"Capacity: {liste.Capacity}"); Console.WriteLine($"Count: {liste.Count}"); foreach (var item in liste) { Console.Write(item + " "); } //Silme işlemi liste.Remove("dsds"); Console.WriteLine($"----Güncelleme-----"); Console.WriteLine($"Capacity: {liste.Capacity}"); Console.WriteLine($"Count: {liste.Count}"); foreach (var item in liste) { Console.Write(item + " "); } //Silme işleme indexli liste.RemoveAt(0); Console.WriteLine($"----Güncellem-----"); Console.WriteLine($"Capacity: {liste.Capacity}"); Console.WriteLine($"Count: {liste.Count}"); foreach (var item in liste) { Console.Write(item + " "); } //silme 3 liste.RemoveRange(0, 2); Console.WriteLine($"----Güncellem-----"); Console.WriteLine($"Capacity: {liste.Capacity}"); Console.WriteLine($"Count: {liste.Count}"); foreach (var item in liste) { Console.Write(item + " "); } //trimtosize liste.TrimToSize(); Console.WriteLine($"----Güncellem-----"); Console.WriteLine($"Capacity: {liste.Capacity}"); Console.WriteLine($"Count: {liste.Count}"); //AddRange var dizi = new int[4] { 1, 2, 3, 4 }; liste.AddRange(dizi); Guncelle(liste); ArrayList liste2 = new ArrayList() { 1, 2, 3 }; liste.AddRange(liste2); liste.AddRange(dizi); Console.WriteLine(" AddRange(ArrayList)"); Guncelle(liste); //Clear //Console.WriteLine("Clear dan sonra"); //liste.Clear(); //Guncelle(liste); //Contains Console.WriteLine("Contains den sonra"); bool varmi = liste.Contains(3); Console.WriteLine($"3 var mı :{varmi}"); //index of tan sonra Console.WriteLine("İndexof dan sonra"); int bulananIndis = liste.IndexOf(3); Console.WriteLine($"3 nerde :{bulananIndis}"); //insert Console.WriteLine("insert 77"); liste.Insert(bulananIndis, 77); Guncelle(liste); //setrange Console.WriteLine("setrange den sonra"); liste.SetRange(0, liste2); Console.WriteLine("liste2"); Guncelle(liste2); Guncelle(liste); }
public void TestSetRange() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; ArrayList arrSetRange = null; int start = 3; string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Wildcat", "Wonder Woman", };//22 string[] strSetRange = { "Hardware", "Icon", "Johnny Quest", "Captain Sisko", "Captain Picard", "Captain Kirk", "Agent J", "Agent K", "Space Ghost", "Wolverine", "Cyclops", "Storm", "Lone Ranger", "Tonto", "Supergirl", };//15 // Construct ArrayList. arrList = new ArrayList((ICollection)strHeroes); arrSetRange = new ArrayList((ICollection)strSetRange); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)ArrayList.FixedSize(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone() }; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // SetRange entire array list. arrList.SetRange(start, arrSetRange); // Verify set. for (int ii = 0; ii < arrSetRange.Count; ++ii) { Assert.Equal(0, ((string)arrList[start + ii]).CompareTo((String)arrSetRange[ii])); } // // [] Attempt invalid SetRange using collection that exceed valid range. // Assert.Throws <ArgumentOutOfRangeException>(() => arrList.SetRange(start, arrList)); // // [] Attempt invalid SetRange using negative index // Assert.Throws <ArgumentOutOfRangeException>(() => arrList.SetRange(-100, arrSetRange)); // // [] Attempt SetRange using out of range index // Assert.Throws <ArgumentOutOfRangeException>(() => arrList.SetRange(1000, arrSetRange)); // // [] Attempt SetRange using null collection. // Assert.Throws <ArgumentNullException>(() => arrList.SetRange(0, null)); } }
static void Main(string[] args) { //Namespace System.Collections //Method 1: ArrayList.Reverse // Creates and initializes a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add("The"); myAL.Add("quick"); myAL.Add("brown"); myAL.Add("fox"); myAL.Add("jumps"); myAL.Add("over"); myAL.Add("the"); myAL.Add("lazy"); myAL.Add("dog"); // Displays the values of the ArrayList. Console.WriteLine("The ArrayList initially contains the following values:"); PrintValues(myAL); // Reverses the sort order of the values of the ArrayList. myAL.Reverse(); // Displays the values of the ArrayList. Console.WriteLine("After reversing:"); PrintValues(myAL); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.reverse?view=netframework-4.8#System_Collections_ArrayList_Reverse Console.WriteLine("\nPress Enter to Continue to my Example"); Console.ReadLine(); ArrayList intarr = new ArrayList { 1, 2, 3, 4, 5 }; //Made my own list. PrintValues(intarr); //Using method from Referenced source to display Array list. intarr.Reverse(); //Method to reverse the list. PrintValues(intarr); //Using method from Referenced source to display Array list in reverse. Console.WriteLine("\nPress Enter to Continue"); Console.ReadLine(); //Method 2: ArrayList.Sort Method Console.WriteLine("The ArrayList initially contains the following values:"); PrintValues(myAL); // Sorts the values of the ArrayList. myAL.Sort(); // Displays the values of the ArrayList. Console.WriteLine("After sorting:"); PrintValues(myAL); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.sort?view=netframework-4.8#System_Collections_ArrayList_Sort Console.WriteLine("\nPress Enter to Continue to my Example"); Console.ReadLine(); ArrayList myUnorgArr = new ArrayList { "Tyler", "Trevor", "Tarra", "Tanner", "Amanda" }; //Made my own list. PrintValues(myUnorgArr); //Using method from Referenced source to display Array list. myUnorgArr.Sort(); //Sorts array in alphabetical order. PrintValues(myUnorgArr); //Using method from Referenced source to display Array list sorted. Console.WriteLine("\nPress Enter to Continue"); Console.ReadLine(); //Method 3: Object.GetType Method object a = "hello"; //created a string variable. Console.WriteLine("Identifying the type:\n\nobject o = myDerived: Type is {0}", a.GetType()); //displays the data type of variable a. Console.WriteLine("\nPress Enter to Continue to my Example"); Console.ReadLine(); Console.WriteLine("myUnorgArr type is {0}", myUnorgArr.GetType());// displays the data type of variable myUnorgArr. Console.WriteLine("\nPress Enter to Continue"); Console.ReadLine(); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.object.gettype?view=netframework-4.8#System_Object_GetType //Method 4: ArrayList.GetRange(Int32, Int32) Method // Creates and initializes the source ICollection. Queue mySourceList = new Queue(); mySourceList.Enqueue("big"); mySourceList.Enqueue("gray"); mySourceList.Enqueue("wolf"); // Displays the values of five elements starting at index 0 From myAL array list from before. ArrayList mySubAL = myAL.GetRange(0, 5); Console.WriteLine("Index 0 through 4 contains:"); PrintValues(mySubAL, '\t'); // Replaces the values of five elements starting at index 1 with the values in the ICollection. myAL.SetRange(1, mySourceList); // Displays the values of five elements starting at index 0. mySubAL = myAL.GetRange(0, 5); Console.WriteLine("Index 0 through 4 now contains:"); PrintValues(mySubAL, '\t'); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.getrange?view=netframework-4.8#System_Collections_ArrayList_GetRange_System_Int32_System_Int32_ Console.WriteLine("\nPress Enter to Continue to my Example"); Console.ReadLine(); Console.WriteLine("This pulled Index 0 through 1 from my example ArrayList"); PrintValues(myUnorgArr.GetRange(0, 2));//Pulls two first two obects in the array list starting from the 0 index. Console.WriteLine("\nPress Enter to Continue"); Console.ReadLine(); //Method 5: // Creates and initializes a new ArrayList. // Displays the values of the ArrayList. Console.WriteLine("The ArrayList contains the following values:"); PrintIndexAndValues(myAL); // Copies the elements of the ArrayList to a string array. String[] myArr = (String[])myAL.ToArray(typeof(string)); // Displays the contents of the string array. Console.WriteLine("The string array contains the following values:"); PrintIndexAndValues(myArr); Console.WriteLine("\nPress Enter to Continue to my Example"); Console.ReadLine(); ArrayList aArrL = myUnorgArr; String[] aArr = (String[])aArrL.ToArray(typeof(string)); Console.WriteLine("The string array I created contains the following values:"); PrintIndexAndValues(aArrL); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.toarray?view=netframework-4.8#System_Collections_ArrayList_ToArray_System_Type_ //Namespace: System //Method 1: string.trim Method //Commonly used to remove whitespace from the outside of strings, but can remove other unwanted characters from a string. //Takes in a string value and returns a string value //identifying characters to remove char[] charsToTrim = { '*', ' ', '\'' }; //initial string variable string banner = "*** Much Ado About Nothing ***"; //calling the trim method and attching it to banner. passing the character array through the parameters string result = banner.Trim(charsToTrim); //Outputting the differences between the result and the original string Console.WriteLine("Trimmmed\n {0}\nto\n '{1}'", banner, result); Console.WriteLine("\nMy Example"); //My Example //Set a string string myStrVar = "! Hello User !"; //Call the method string myTrim = myStrVar.Trim(' ', '!'); // Output the result Console.WriteLine("\nMy Example:\n{0}\nTo\n'{1}'", myStrVar, myTrim); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.trim?view=netframework-4.8#System_String_Trim_System_Char___ Console.WriteLine("Press enter to continue"); Console.ReadLine(); //Method 2: Char.IsWhiteSpace Method //This method will identify if the character selected is 'whitespace', //It returns a boolean value //Insert a string value in the parameters and the character index you wan to test //Note: if you select a string str = "black matter"; Console.WriteLine("------------------------"); Console.WriteLine("Finding the white space in, '{0}' \nand return a boolean expression if in the 1 index", str); Console.WriteLine(Char.IsWhiteSpace(str, 1)); // Output: "False" Console.WriteLine("------------------------"); Console.WriteLine("Finding the white space in, '{0}' \nand return a boolean expression if in the 5 index", str); Console.WriteLine(Char.IsWhiteSpace(str, 5)); // Output: "True" Console.WriteLine("------------------------"); string x = "01234 6789"; Console.WriteLine("Finding the white space in, '{0}' \nand return a boolean expression if in the 5 index", x); Console.WriteLine("\nMy Example:\n" + Char.IsWhiteSpace(x, 5)); //Output: "True" Console.WriteLine("Press enter to continue"); Console.ReadLine(); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace?view=netframework-4.8 //Method 3: Array.Exists method //This method passes elements from an array individually through other methods in the other parameter. //It returns boolean expresions and the method is a O(n) operation where n is the length of the array String[] names = { "Adam", "Adel", "Bridgette", "Carla", "Charles", "Daniel", "Elaine", "Frances", "George", "Gillian", "Henry", "Irving", "James", "Janae", "Lawrence", "Miguel", "Nicole", "Oliver", "Paula", "Robert", "Stephen", "Thomas", "Vanessa", "Veronica", "Wilberforce" }; Char[] charsToFind = { 'A', 'K', 'W', 'Z' };//Assigns character values Console.WriteLine($"Within the array"); foreach (var charToFind in charsToFind) { Console.WriteLine("One or more names begin with '{0}': {1}", charToFind, Array.Exists(names,//The first parameter is the array and the second parameter is pulling the character out of the string in the array s => { if (String.IsNullOrEmpty(s)) //If the value is null or empty it will return false { return(false); } if (s.Substring(0, 1).ToUpper() == charToFind.ToString()) //Takes one input at the 0 index and if equal to the characters above then the value is true { return(true); } else //I neither is true then it is false { return(false); } })); } //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.exists?view=netframework-4.8 Console.WriteLine("Press enter to continue"); Console.ReadLine(); //Method 4: Array.Find<T>(T[], Predicate<T>) Method // Create an array of five Point structures. //Useing System drawings Point[] points = { new Point(100, 200), new Point(150, 250),new Point(250, 375), new Point(275, 395),new Point(295, 450) }; // Find the first Point structure for which X times Y // is greater than 100000. Point first = Array.Find(points, p => p.X * p.Y > 100000); // Display the first structure found. Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.find?view=netframework-4.8 Console.WriteLine("\nPress Enter to Continue to my Example"); Console.ReadLine(); Console.WriteLine("\nMy Example"); //My Example: string[] mooreFamNames = { "Tyler", "Trevor", "Tarra", "Tanner", "Amanda" }; Console.WriteLine("\nMy Array:"); foreach (var item in mooreFamNames) { Console.Write("{0},\n", item); } Console.WriteLine("In my array I searched for the name that started with 'A'"); string mooreFinder = Array.Find(mooreFamNames, namees => namees.StartsWith("A", StringComparison.Ordinal)); Console.WriteLine(mooreFinder); //Method 5: StartsWith(String) string[] strSource = { "<b>This is bold text</b>", "<H1>This is large Text</H1>", "<b><i><font color=green>This has multiple tags</font></i></b>", "<b>This has <i>embedded</i> tags.</b>", "<This line simply begins with a lesser than symbol, it should not be modified" }; // Display the initial string array. Console.WriteLine("The original strings:"); Console.WriteLine("---------------------"); foreach (var s in strSource) { Console.WriteLine(s); } Console.WriteLine(); Console.WriteLine("Strings after starting tags have been stripped:"); Console.WriteLine("-----------------------------------------------"); // Display the strings with starting tags removed. foreach (var s in strSource) { Console.WriteLine(StripStartTags(s)); } //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.startswith?view=netframework-4.8#System_String_StartsWith_System_String_ Console.WriteLine("\nPress Enter to Continue to my Example"); Console.ReadLine(); //My Example Console.WriteLine(); Console.WriteLine("-----------------------------------------------"); Console.WriteLine("\nMy Example\nI send the array through the four loop\nto find the name that starts with 'A'"); string[] burchFamName = { "Amanda", "Jordan", "Dan", "Mel" }; for (int i = 0; i < burchFamName.Length; i++) { Console.WriteLine("Inside my other Array: {0}", burchFamName[i]); } Console.WriteLine(); Console.WriteLine("\nMy Example\nI send the array through the four loop\nto find the name that starts with 'A'\nAnswer:"); for (int i = 0; i < burchFamName.Length; i++) { burchFamName[i].ToUpper(); if (burchFamName[i].StartsWith("A")) { Console.WriteLine(burchFamName[i]); } } Console.WriteLine("-----------------------------------------------"); //NameSpace : System.Math Methods //Method 1: Absolute Value Method Console.WriteLine("\nThis example shows the:\nMath.Abs Method\n------------------------------ "); int[] values = { Int32.MaxValue, 16921, 0, -804128, Int32.MinValue }; foreach (int value in values) { try { Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); } catch (OverflowException) { Console.WriteLine("Unable to calculate the absolute value of {0}.", value); } } Console.WriteLine("\nPress Enter to Continue"); Console.ReadLine(); Console.WriteLine("\nThis example shows the:\nMath.BigMul(Int32, Int32) Method\n------------------------------ "); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.8 //Method 2: Math.BigMul(Int32, Int32) Method int int1 = Int32.MaxValue; int int2 = Int32.MaxValue; long longResult; // longResult = Math.BigMul(int1, int2); Console.WriteLine("Calculate the product of two Int32 values:"); Console.WriteLine("{0} * {1} = {2}", int1, int2, longResult); /*This example produces the following results: * Calculate the product of two Int32 values: * 2147483647 * 2147483647 = 4611686014132420609*/ Console.WriteLine("\nPress Enter to Continue"); Console.ReadLine(); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.bigmul?view=netframework-4.8 // //This is an example that determines wich int variable is the highest. //Method 3: Math.Max() Method Console.WriteLine("\nThis example shows the:\nMath.Max Method\n------------------------------ "); int num1 = 45; int num2 = 54; Console.WriteLine("Between the numbers {0} and {1}: {2} is the highest", num2, num1, Math.Max(num1, num2)); //Reference:https://docs.microsoft.com/en-us/dotnet/api/system.math.max?view=netframework-4.8#System_Math_Max_System_UInt32_System_UInt32_ Console.WriteLine("\nPress Enter to Continue"); Console.ReadLine(); //Method 4: Math.Min() Method //This is an example that determines wich int variable is the lowest. Console.WriteLine("\nThis example shows the:\nMath.Min Method\n------------------------------ "); Console.WriteLine("Between the numbers {0} and {1}: {2} is the lowest", num1, num2, Math.Min(num1, num2)); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.min?view=netcore-3.1#System_Math_Min_System_Int32_System_Int32_ Console.WriteLine("\nPress Enter to Continue"); Console.ReadLine(); //Method 5: Math.Sqrt() Method double mydub = 2911231; Math.Sqrt(mydub); Console.WriteLine("\nThis example shows the:\nMath.Sqrt Method\n------------------------------ "); Console.WriteLine("The number {0} is the square root of {1}", Math.Sqrt(mydub), mydub); //Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.sqrt?view=netcore-3.1 }
private void CompareObjects(ArrayList good, ArrayList bad, Hashtable hsh1) { DoIListTests(good, bad, hsh1); good.Clear(); for(int i=0; i<100; i++) good.Add(i); if(fVerbose) Console.WriteLine("CopyTo()"); Int32[] iArr1 = null; Int32[] iArr2 = null; iArr1 = new Int32[100]; iArr2 = new Int32[100]; good.CopyTo(iArr1); bad.CopyTo(iArr2); for(int i=0; i<100; i++) { if(iArr1[i] != iArr2[i]) hsh1["CopyTo"] = "()"; } iArr1 = new Int32[100]; iArr2 = new Int32[100]; good.CopyTo(0, iArr1, 0, 100); try { bad.CopyTo(0, iArr2, 0, 100); for(int i=0; i<100; i++) { if(iArr1[i] != iArr2[i]) hsh1["CopyTo"] = "()"; } } catch { hsh1["CopyTo"] = "(Int32, Array, Int32, Int32)"; } iArr1 = new Int32[200]; iArr2 = new Int32[200]; for(int i=0; i<200; i++) { iArr1[i]=50; iArr2[i]=50; } good.CopyTo(50, iArr1, 100, 20); try { bad.CopyTo(50, iArr2, 100, 20); for(int i=0; i<200; i++) { if(iArr1[i] != iArr2[i]) hsh1["CopyTo"] = "(Array, Int32, Int32)"; } } catch { hsh1["CopyTo"] = "(Int32, Array, Int32, Int32)"; } if(fVerbose) Console.WriteLine("Clone()"); ArrayList alstClone = (ArrayList)bad.Clone(); if(alstClone.Count != bad.Count) hsh1["Clone"] = "Count"; for(int i=0; i<bad.Count; i++) { if(alstClone[i] != bad[i]) hsh1["Clone"] = "[]"; } if(fVerbose) Console.WriteLine("GetEnumerator()"); IEnumerator ienm1 = null; IEnumerator ienm2 = null; ienm1 = good.GetEnumerator(0, 100); try { ienm2 = bad.GetEnumerator(0, 100); DoIEnumerableTest(ienm1, ienm2, hsh1, false); } catch { hsh1["GetEnumerator"] = "(Int32, Int32)"; } ienm1 = good.GetEnumerator(50, 50); try { ienm2 = bad.GetEnumerator(50, 50); DoIEnumerableTest(ienm1, ienm2, hsh1, false); } catch { hsh1["GetEnumerator"] = "(Int32, Int32)"; } try { bad.GetEnumerator(50, 150); hsh1["GetEnumerator"] = "(Int32, Int32)"; } catch(Exception) { } ienm1 = good.GetEnumerator(0, 100); try { ienm2 = bad.GetEnumerator(0, 100); good.RemoveAt(0); DoIEnumerableTest(ienm1, ienm2, hsh1, true); } catch { hsh1["GetEnumerator"] = "(Int32, Int32)"; } good.Clear(); for(int i=0; i<100; i++) good.Add(i); if(fVerbose) Console.WriteLine("GetRange()"); ArrayList alst1 = good.GetRange(0, good.Count); try { ArrayList alst2 = bad.GetRange(0, good.Count); for(int i=0; i<good.Count; i++) { if(alst1[i] != alst2[i]) hsh1["GetRange"] = i; } } catch { hsh1["Range"] = "(Int32, Int32)"; } if(bad.Count>0) { if(fVerbose) Console.WriteLine("IndexOf()"); for(int i=0; i<good.Count; i++) { if(good.IndexOf(good[i], 0) != bad.IndexOf(good[i], 0)) { Console.WriteLine(good .Count + " " + bad.Count + " " + good[i] + " " + bad[i] + " " + good.IndexOf(good[i], 0) + " " + bad.IndexOf(good[i], 0)); hsh1["IndexOf"] = "(Object, Int32)"; } if(good.IndexOf(good[i], i) != bad.IndexOf(good[i], i)) { Console.WriteLine("2" + good.IndexOf(good[i], i) + " " + bad.IndexOf(good[i], i)); hsh1["IndexOf"] = "(Object, Int32)"; } if(i<(good.Count-1)) { if(good.IndexOf(good[i], i+1) != bad.IndexOf(good[i], i+1)) { Console.WriteLine("3" + good.IndexOf(good[i], i+1) + " " + bad.IndexOf(good[i], i+1)); hsh1["IndexOf"] = "(Object, Int32)"; } } } try { bad.IndexOf(1, -1); } catch(ArgumentException) { } catch(Exception ex) { hsh1["IndexOf"] = ex; } try { bad.IndexOf(1, bad.Count); } catch(ArgumentException) { } catch(Exception ex) { hsh1["IndexOf"] = ex; } for(int i=0; i<good.Count; i++) { if(good.IndexOf(good[i], 0, good.Count-1) != bad.IndexOf(good[i], 0, good.Count-1)) { hsh1["IndexOf"] = "(Object, Int32, Int32)"; } if(good.IndexOf(good[i], i, good.Count-i) != bad.IndexOf(good[i], i, good.Count-i)) { hsh1["IndexOf"] = "(Object, Int32)"; } if(good.IndexOf(good[i], i, 0) != bad.IndexOf(good[i], i, 0)) { hsh1["IndexOf"] = "(Object, Int32)"; } if(i<(good.Count-1)) { if(good.IndexOf(good[i], i+1, good.Count-(i+1)) != bad.IndexOf(good[i], i+1, good.Count-(i+1))) { hsh1["IndexOf"] = "(Object, Int32)"; } } } try { bad.IndexOf(1, 0, -1); } catch(ArgumentException) { } catch(Exception ex) { hsh1["IndexOf"] = ex; } try { bad.IndexOf(1, 0, bad.Count); } catch(ArgumentException) { } catch(Exception ex) { hsh1["IndexOf"] = ex; } try { bad.IndexOf(1, bad.Count-1, bad.Count-2); } catch(ArgumentException) { } catch(Exception ex) { hsh1["IndexOf"] = ex; } if(fVerbose) Console.WriteLine("LastIndexOf(), " + good.Count + " " + bad.Count); for(int i=0; i<good.Count; i++) { if(good.LastIndexOf(good[i]) != bad.LastIndexOf(good[i])) { hsh1["LastIndexOf"] = "(Object)"; } if(good.LastIndexOf(i+1000) != bad.LastIndexOf(i+1000)) { hsh1["LastIndexOf"] = "(Object)"; } } try { bad.LastIndexOf(null); } catch(ArgumentException) { } catch(Exception ex) { hsh1["LastIndexOf"] = ex; } if(fVerbose) Console.WriteLine("LastIndexOf(Object, Int32)"); for(int i=0; i<good.Count; i++) { if(good.LastIndexOf(good[i], good.Count-1) != bad.LastIndexOf(good[i], good.Count-1)) { hsh1["LastIndexOf"] = "(Object, Int32)"; } if(good.LastIndexOf(good[i], 0) != bad.LastIndexOf(good[i], 0)) { hsh1["LastIndexOf"] = "(Object, Int32)"; } if(good.LastIndexOf(good[i], i) != bad.LastIndexOf(good[i], i)) { hsh1["LastIndexOf"] = "(Object, Int32)"; } if(i<(good.Count-1)) { if(good.LastIndexOf(good[i], i+1) != bad.LastIndexOf(good[i], i+1)) { hsh1["LastIndexOf"] = "(Object, Int32)"; } } } try { bad.LastIndexOf(1, -1); } catch(ArgumentException) { } catch(Exception ex) { hsh1["LastIndexOf"] = ex; } try { bad.LastIndexOf(1, bad.Count); } catch(ArgumentException) { } catch(Exception ex) { hsh1["LastIndexOf"] = ex; } for(int i=0; i<good.Count; i++) { if(good.LastIndexOf(good[i], good.Count-1, 0) != bad.LastIndexOf(good[i], good.Count-1, 0)) { hsh1["LastIndexOf"] = "(Object, Int32, Int32)"; } if(good.LastIndexOf(good[i], good.Count-1, i) != bad.LastIndexOf(good[i], good.Count-1, i)) { hsh1["LastIndexOf"] = "(Object, Int32)"; } if(good.LastIndexOf(good[i], i, i) != bad.LastIndexOf(good[i], i, i)) { hsh1["LastIndexOf"] = "(Object, Int32)"; } if(i<(good.Count-1)) { if(good.LastIndexOf(good[i], good.Count-1, i+1) != bad.LastIndexOf(good[i], good.Count-1, i+1)) { hsh1["LastIndexOf"] = "(Object, Int32)"; } } } try { bad.LastIndexOf(1, 1, -1); } catch(ArgumentException) { } catch(Exception ex) { hsh1["LastIndexOf"] = ex; } try { bad.LastIndexOf(1, bad.Count-2, bad.Count-1); } catch(ArgumentException) { } catch(Exception ex) { hsh1["LastIndexOf"] = ex; } } if(fVerbose) Console.WriteLine("ReadOnly()"); ArrayList alst3 = ArrayList.ReadOnly(bad); if(!alst3.IsReadOnly) hsh1["ReadOnly"] = "Not"; IList ilst1 = ArrayList.ReadOnly((IList)bad); if(!ilst1.IsReadOnly) hsh1["ReadOnly"] = "Not"; if(fVerbose) Console.WriteLine("Synchronized()"); alst3 = ArrayList.Synchronized(bad); if(!alst3.IsSynchronized) hsh1["Synchronized"] = "Not"; ilst1 = ArrayList.Synchronized((IList)bad); if(!ilst1.IsSynchronized) hsh1["Synchronized"] = "Not"; if(good.Count == bad.Count) { if(fVerbose) Console.WriteLine("ToArray()"); Object[] oArr1 = good.ToArray(); Object[] oArr2 = bad.ToArray(); for(int i=0; i<good.Count; i++) { if((Int32)oArr1[i] != (Int32)oArr2[i]) hsh1["ToArray"] = "()"; } iArr1 = (Int32[])good.ToArray(typeof(Int32)); iArr2 = (Int32[])bad.ToArray(typeof(Int32)); for(int i=0; i<good.Count; i++) { if(iArr1[i] != iArr2[i]) hsh1["ToArray"] = "(Type)"; } } if(fVerbose) Console.WriteLine("Capacity()"); if(good.Capacity != bad.Capacity) { hsh1["Capacity"] = "get"; } if(!hsh1.ContainsKey("IsReadOnly")) { good.Clear(); for(int i=100; i>0; i--) good.Add(i); if(fVerbose) Console.WriteLine("Sort() & BinarySearch()"); bad.Sort(); for(int i=0; i<bad.Count-1; i++) { if((Int32)bad[i] > (Int32)bad[i+1]) hsh1["Sort"] = "()"; } for(int i=0; i<bad.Count; i++) { if(bad.BinarySearch(bad[i]) != i) hsh1["BinarySearch"] = "(Object)"; } bad.Reverse(); if(bad.Count>0) { for(int i=0; i<99; i++) { if((Int32)bad[i] < (Int32)bad[i+1]) hsh1["Reverse"] = "()"; } good.Clear(); for(int i=100; i>0; i--) good.Add(i.ToString()); } good.Clear(); for(int i=90; i>64; i--) good.Add(((Char)i).ToString()); try { bad.Sort(new CaseInsensitiveComparer()); if(bad.Count>0) { for(int i=0; i<(bad.Count-1); i++) { if(((String)bad[i]).CompareTo(((String)bad[i+1])) >= 0) hsh1["Sort"] = "(IComparer)"; } for(int i=0; i<bad.Count; i++) { if(bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i) hsh1["BinarySearch"] = "(Object, IComparer)"; } } bad.Reverse(); good.Clear(); for(int i=65; i<91; i++) good.Add(((Char)i).ToString()); if(bad.Count>0) { for(int i=0; i<good.Count; i++) { if(bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i) hsh1["BinarySearch"] = "(Int32, Int32, Object, IComparer)"; } } } catch(Exception) { } good.Clear(); for(int i=0; i<100; i++) good.Add(i); if(fVerbose) Console.WriteLine("SetRange()"); Queue que = new Queue(); for(int i=0; i<100; i++) que.Enqueue(i+5000); try { bad.SetRange(0, que); } catch(Exception ex) { hsh1["SetRange"] = "Copy_ExceptionType, " + ex.GetType().Name; } for(int i=bad.Count; i<bad.Count; i++) { if((Int32)bad[i] != (i + 5000)) { hsh1["SetRange"] = i; } } } else { good.Clear(); for(int i=100; i>0; i--) good.Add(i); try { bad.Sort(); hsh1["Sort"] = "Copy"; } catch(NotSupportedException) { } catch(Exception) { hsh1["Sort"] = "Copy_ExceptionType"; } try { bad.Reverse(); hsh1["Reverse"] = "Copy"; } catch(NotSupportedException) { } catch(Exception ex) { hsh1["Reverse"] = "Copy_ExceptionType, " + ex.GetType().Name; } try { bad.Sort(new CaseInsensitiveComparer()); hsh1["Sort"] = "Copy - Icomparer"; } catch(NotSupportedException) { } catch(Exception) { hsh1["Sort"] = "Copy_ExceptionType"; } try { bad.Sort(0, 0, new CaseInsensitiveComparer()); hsh1["Sort"] = "Copy - Int32, Int32, IComparer"; } catch(NotSupportedException) { } catch(Exception) { hsh1["Sort"] = "Copy_ExceptionType"; } try { for(int i=0; i<bad.Count; i++) { if(bad.BinarySearch(bad[i]) != i) hsh1["BinarySearch"] = "(Object)"; } hsh1["BinarySearch"] = "(Object)"; } catch(NotSupportedException) { } catch(Exception ex) { hsh1["BinarySearch"] = ex.GetType().Name; } try { for(int i=0; i<bad.Count; i++) { if(bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i) hsh1["BinarySearch"] = "(Object)"; } hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)"; } catch(NotSupportedException) { } catch(Exception ex) { hsh1["BinarySearch"] = ex.GetType().Name; } try { for(int i=0; i<bad.Count; i++) { if(bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i) hsh1["BinarySearch"] = "(Object)"; } hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)"; } catch(NotSupportedException) { } catch(Exception ex) { hsh1["BinarySearch"] = ex.GetType().Name; } good.Clear(); for(int i=0; i<100; i++) good.Add(i); Queue que = new Queue(); for(int i=0; i<100; i++) que.Enqueue(i+5000); try { bad.SetRange(0, que); hsh1["Sort"] = "Copy - Int32, Int32, IComparer"; } catch(NotSupportedException) { } catch(Exception) { hsh1["Sort"] = "Copy_ExceptionType"; } } if(!hsh1.ContainsKey("IsReadOnly") && !hsh1.ContainsKey("Fixed")) { good.Clear(); for(int i=0; i<100; i++) good.Add(i); if(fVerbose) Console.WriteLine("InsertRange()"); Queue que = new Queue(); for(int i=0; i<100; i++) que.Enqueue(i+5000); bad.InsertRange(0, que); for(int i=0; i<100; i++) { if((Int32)bad[i] != i + 5000) { hsh1["InsertRange"] = i; } } if(fVerbose) Console.WriteLine("AddRange()"); que = new Queue(); for(int i=0; i<100; i++) que.Enqueue(i+2222); bad.AddRange(que); for(int i=bad.Count-100; i<bad.Count; i++) { if((Int32)bad[i] != (i-(bad.Count-100)) + 2222) { hsh1["AddRange"] = i + " " + (Int32)bad[i]; } } if(fVerbose) Console.WriteLine("RemoveRange()"); bad.RemoveRange(0, que.Count); for(int i=0; i<100; i++) { if((Int32)bad[i] != i) { hsh1["RemoveRange"] = i + " " + (Int32)bad[i]; } } try { bad.Capacity = bad.Capacity*2; } catch(Exception ex) { hsh1["Capacity"] = ex.GetType().Name; } try { bad.Capacity = -1; hsh1["Capacity"] = "No_Exception_Thrown, -1"; } catch(ArgumentException) { } catch(Exception ex) { hsh1["Capacity"] = ex.GetType().Name; } Int32 iMakeSureThisDoesNotCause = 0; while(bad.Capacity == bad.Count) { if(iMakeSureThisDoesNotCause++>100) break; bad.Add(bad.Count); } if(iMakeSureThisDoesNotCause>100) hsh1["TrimToSize"] = "Monekeyed, " + bad.Count + " " + bad.Capacity; try { bad.TrimToSize(); if(bad.Capacity != bad.Count) { hsh1["TrimToSize"] = "Problems baby"; } } catch(Exception ex) { hsh1["TrimToSize"] = ex.GetType().Name; } } else { Queue que = new Queue(); for(int i=0; i<100; i++) que.Enqueue(i+5000); try { bad.AddRange(que); hsh1["AddRange"] = "Copy"; } catch(NotSupportedException) { } catch(Exception) { hsh1["AddRange"] = "Copy_ExceptionType"; } try { bad.InsertRange(0, que); hsh1["InsertRange"] = "Copy"; } catch(NotSupportedException) { } catch(Exception) { hsh1["InsertRange"] = "Copy_ExceptionType"; } good.Clear(); for(int i=0; i<10; i++) good.Add(i); try { bad.RemoveRange(0, 10); hsh1["RemoveRange"] = "Copy"; } catch(NotSupportedException) { } catch(Exception ex) { hsh1["RemoveRange"] = "Copy_ExceptionType, " + ex.GetType().Name; } try { bad.Capacity = bad.Capacity*2; hsh1["Capacity"] = "No_Exception_Thrown, bad.Capacity*2"; } catch(NotSupportedException) { } catch(Exception ex) { hsh1["Capacity"] = ex.GetType().Name; } try { bad.TrimToSize(); hsh1["TrimToSize"] = "No_Exception_Thrown"; } catch(NotSupportedException) { } catch(Exception ex) { hsh1["TrimToSize"] = ex.GetType().Name; } } }
private void CompareObjects(ArrayList good, ArrayList bad, Hashtable hsh1) { //IList, this includes ICollection tests as well!! DoIListTests(good, bad, hsh1); //we will now test ArrayList specific methods good.Clear(); for (int i = 0; i < 100; i++) good.Add(i); //AL's CopyTo methods int[] iArr1 = null; int[] iArr2 = null; iArr1 = new int[100]; iArr2 = new int[100]; good.CopyTo(iArr1); bad.CopyTo(iArr2); for (int i = 0; i < 100; i++) { if (iArr1[i] != iArr2[i]) hsh1["CopyTo"] = "()"; } iArr1 = new int[100]; iArr2 = new int[100]; good.CopyTo(0, iArr1, 0, 100); try { bad.CopyTo(0, iArr2, 0, 100); for (int i = 0; i < 100; i++) { if (iArr1[i] != iArr2[i]) hsh1["CopyTo"] = "()"; } } catch { hsh1["CopyTo"] = "(int, Array, int, int)"; } iArr1 = new int[200]; iArr2 = new int[200]; for (int i = 0; i < 200; i++) { iArr1[i] = 50; iArr2[i] = 50; } good.CopyTo(50, iArr1, 100, 20); try { bad.CopyTo(50, iArr2, 100, 20); for (int i = 0; i < 200; i++) { if (iArr1[i] != iArr2[i]) hsh1["CopyTo"] = "(Array, int, int)"; } } catch { hsh1["CopyTo"] = "(int, Array, int, int)"; } //Clone() ArrayList alstClone = (ArrayList)bad.Clone(); //lets make sure that the clone is what it says it is if (alstClone.Count != bad.Count) hsh1["Clone"] = "Count"; for (int i = 0; i < bad.Count; i++) { if (alstClone[i] != bad[i]) hsh1["Clone"] = "[]"; } //GerEnumerator() IEnumerator ienm1 = null; IEnumerator ienm2 = null; ienm1 = good.GetEnumerator(0, 100); try { ienm2 = bad.GetEnumerator(0, 100); DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, false); } catch { hsh1["GetEnumerator"] = "(int, int)"; } ienm1 = good.GetEnumerator(50, 50); try { ienm2 = bad.GetEnumerator(50, 50); DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, false); } catch { hsh1["GetEnumerator"] = "(int, int)"; } try { bad.GetEnumerator(50, 150); hsh1["GetEnumerator"] = "(int, int)"; } catch (Exception) { } ienm1 = good.GetEnumerator(0, 100); try { ienm2 = bad.GetEnumerator(0, 100); good.RemoveAt(0); DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, true); } catch { hsh1["GetEnumerator"] = "(int, int)"; } //GetRange good.Clear(); for (int i = 0; i < 100; i++) good.Add(i); ArrayList alst1 = good.GetRange(0, good.Count); try { ArrayList alst2 = bad.GetRange(0, good.Count); for (int i = 0; i < good.Count; i++) { if (alst1[i] != alst2[i]) hsh1["GetRange"] = i; } } catch { hsh1["Range"] = "(int, int)"; } //IndexOf(Object, int) if (bad.Count > 0) { for (int i = 0; i < good.Count; i++) { if (good.IndexOf(good[i], 0) != bad.IndexOf(good[i], 0)) { hsh1["IndexOf"] = "(Object, int)"; } if (good.IndexOf(good[i], i) != bad.IndexOf(good[i], i)) { hsh1["IndexOf"] = "(Object, int)"; } if (i < (good.Count - 1)) { if (good.IndexOf(good[i], i + 1) != bad.IndexOf(good[i], i + 1)) { hsh1["IndexOf"] = "(Object, int)"; } } } try { bad.IndexOf(1, -1); } catch (ArgumentException) { } catch (Exception ex) { hsh1["IndexOf"] = ex; } try { bad.IndexOf(1, bad.Count); } catch (ArgumentException) { } catch (Exception ex) { hsh1["IndexOf"] = ex; } // IndexOf(Object, int, int) // The semantics of this method has changed, the 3rd parameter now refers to count instead of length for (int i = 0; i < good.Count; i++) { if (good.IndexOf(good[i], 0, good.Count - 1) != bad.IndexOf(good[i], 0, good.Count - 1)) { hsh1["IndexOf"] = "(Object, int, int)"; } if (good.IndexOf(good[i], i, good.Count - i) != bad.IndexOf(good[i], i, good.Count - i)) { hsh1["IndexOf"] = "(Object, int)"; } if (good.IndexOf(good[i], i, 0) != bad.IndexOf(good[i], i, 0)) { hsh1["IndexOf"] = "(Object, int)"; } if (i < (good.Count - 1)) { if (good.IndexOf(good[i], i + 1, good.Count - (i + 1)) != bad.IndexOf(good[i], i + 1, good.Count - (i + 1))) { hsh1["IndexOf"] = "(Object, int)"; } } } try { bad.IndexOf(1, 0, -1); } catch (ArgumentException) { } catch (Exception ex) { hsh1["IndexOf"] = ex; } try { bad.IndexOf(1, 0, bad.Count); } catch (ArgumentException) { } catch (Exception ex) { hsh1["IndexOf"] = ex; } try { bad.IndexOf(1, bad.Count - 1, bad.Count - 2); } catch (ArgumentException) { } catch (Exception ex) { hsh1["IndexOf"] = ex; } //LastIndexOf(Object) for (int i = 0; i < good.Count; i++) { if (good.LastIndexOf(good[i]) != bad.LastIndexOf(good[i])) { hsh1["LastIndexOf"] = "(Object)"; } if (good.LastIndexOf(i + 1000) != bad.LastIndexOf(i + 1000)) { hsh1["LastIndexOf"] = "(Object)"; } } try { bad.LastIndexOf(null); } catch (ArgumentException) { } catch (Exception ex) { hsh1["LastIndexOf"] = ex; } //LastIndexOf(Object, int) for (int i = 0; i < good.Count; i++) { if (good.LastIndexOf(good[i], good.Count - 1) != bad.LastIndexOf(good[i], good.Count - 1)) { hsh1["LastIndexOf"] = "(Object, int)"; } if (good.LastIndexOf(good[i], 0) != bad.LastIndexOf(good[i], 0)) { hsh1["LastIndexOf"] = "(Object, int)"; } if (good.LastIndexOf(good[i], i) != bad.LastIndexOf(good[i], i)) { hsh1["LastIndexOf"] = "(Object, int)"; } if (i < (good.Count - 1)) { if (good.LastIndexOf(good[i], i + 1) != bad.LastIndexOf(good[i], i + 1)) { hsh1["LastIndexOf"] = "(Object, int)"; } } } try { bad.LastIndexOf(1, -1); } catch (ArgumentException) { } catch (Exception ex) { hsh1["LastIndexOf"] = ex; } try { bad.LastIndexOf(1, bad.Count); } catch (ArgumentException) { } catch (Exception ex) { hsh1["LastIndexOf"] = ex; } //LastIndexOf(Object, int, int) for (int i = 0; i < good.Count; i++) { if (good.LastIndexOf(good[i], good.Count - 1, 0) != bad.LastIndexOf(good[i], good.Count - 1, 0)) { hsh1["LastIndexOf"] = "(Object, int, int)"; } if (good.LastIndexOf(good[i], good.Count - 1, i) != bad.LastIndexOf(good[i], good.Count - 1, i)) { hsh1["LastIndexOf"] = "(Object, int)"; } if (good.LastIndexOf(good[i], i, i) != bad.LastIndexOf(good[i], i, i)) { hsh1["LastIndexOf"] = "(Object, int)"; } if (i < (good.Count - 1)) { if (good.LastIndexOf(good[i], good.Count - 1, i + 1) != bad.LastIndexOf(good[i], good.Count - 1, i + 1)) { hsh1["LastIndexOf"] = "(Object, int)"; } } } try { bad.LastIndexOf(1, 1, -1); } catch (ArgumentException) { } catch (Exception ex) { hsh1["LastIndexOf"] = ex; } try { bad.LastIndexOf(1, bad.Count - 2, bad.Count - 1); } catch (ArgumentException) { } catch (Exception ex) { hsh1["LastIndexOf"] = ex; } } //ReadOnly() ArrayList alst3 = ArrayList.ReadOnly(bad); if (!alst3.IsReadOnly) hsh1["ReadOnly"] = "Not"; IList ilst1 = ArrayList.ReadOnly((IList)bad); if (!ilst1.IsReadOnly) hsh1["ReadOnly"] = "Not"; //Synchronized() alst3 = ArrayList.Synchronized(bad); if (!alst3.IsSynchronized) hsh1["Synchronized"] = "Not"; ilst1 = ArrayList.Synchronized((IList)bad); if (!ilst1.IsSynchronized) hsh1["Synchronized"] = "Not"; //ToArray() if (good.Count == bad.Count) { object[] oArr1 = good.ToArray(); object[] oArr2 = bad.ToArray(); for (int i = 0; i < good.Count; i++) { if ((int)oArr1[i] != (int)oArr2[i]) hsh1["ToArray"] = "()"; } //ToArray(type) iArr1 = (int[])good.ToArray(typeof(int)); iArr2 = (int[])bad.ToArray(typeof(int)); for (int i = 0; i < good.Count; i++) { if (iArr1[i] != iArr2[i]) hsh1["ToArray"] = "(Type)"; } } //Capacity - get if (good.Capacity != bad.Capacity) { hsh1["Capacity"] = "get"; } //Fixed size methods if (!hsh1.ContainsKey("IsReadOnly")) { good.Clear(); for (int i = 100; i > 0; i--) good.Add(i); //Sort() & BinarySearch(Object) bad.Sort(); for (int i = 0; i < bad.Count - 1; i++) { if ((int)bad[i] > (int)bad[i + 1]) hsh1["Sort"] = "()"; } for (int i = 0; i < bad.Count; i++) { if (bad.BinarySearch(bad[i]) != i) hsh1["BinarySearch"] = "(Object)"; } //Reverse() bad.Reverse(); if (bad.Count > 0) { for (int i = 0; i < 99; i++) { if ((int)bad[i] < (int)bad[i + 1]) hsh1["Reverse"] = "()"; } good.Clear(); for (int i = 100; i > 0; i--) good.Add(i.ToString()); } good.Clear(); for (int i = 90; i > 64; i--) good.Add(((Char)i).ToString()); try { bad.Sort(new CaseInsensitiveComparer()); if (bad.Count > 0) { for (int i = 0; i < (bad.Count - 1); i++) { if (((String)bad[i]).CompareTo(((String)bad[i + 1])) >= 0) hsh1["Sort"] = "(IComparer)"; } for (int i = 0; i < bad.Count; i++) { if (bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i) hsh1["BinarySearch"] = "(Object, IComparer)"; } } bad.Reverse(); good.Clear(); for (int i = 65; i < 91; i++) good.Add(((Char)i).ToString()); if (bad.Count > 0) { for (int i = 0; i < good.Count; i++) { if (bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i) hsh1["BinarySearch"] = "(int, int, Object, IComparer)"; } } } catch (Exception) { } good.Clear(); for (int i = 0; i < 100; i++) good.Add(i); Queue que = new Queue(); for (int i = 0; i < 100; i++) que.Enqueue(i + 5000); try { bad.SetRange(0, que); } catch (Exception ex) { hsh1["SetRange"] = "Copy_ExceptionType, " + ex.GetType().Name; } for (int i = bad.Count; i < bad.Count; i++) { if ((int)bad[i] != (i + 5000)) { hsh1["SetRange"] = i; } } } else { //we make sure that the above methods throw here good.Clear(); for (int i = 100; i > 0; i--) good.Add(i); try { bad.Sort(); hsh1["Sort"] = "Copy"; } catch (NotSupportedException) { } catch (Exception) { hsh1["Sort"] = "Copy_ExceptionType"; } try { bad.Reverse(); hsh1["Reverse"] = "Copy"; } catch (NotSupportedException) { } catch (Exception ex) { hsh1["Reverse"] = "Copy_ExceptionType, " + ex.GetType().Name; } try { bad.Sort(new CaseInsensitiveComparer()); hsh1["Sort"] = "Copy - Icomparer"; } catch (NotSupportedException) { } catch (Exception) { hsh1["Sort"] = "Copy_ExceptionType"; } try { bad.Sort(0, 0, new CaseInsensitiveComparer()); hsh1["Sort"] = "Copy - int, int, IComparer"; } catch (NotSupportedException) { } catch (Exception) { hsh1["Sort"] = "Copy_ExceptionType"; } //BinarySearch try { for (int i = 0; i < bad.Count; i++) { if (bad.BinarySearch(bad[i]) != i) hsh1["BinarySearch"] = "(Object)"; } hsh1["BinarySearch"] = "(Object)"; } catch (NotSupportedException) { } catch (Exception ex) { hsh1["BinarySearch"] = ex.GetType().Name; } try { for (int i = 0; i < bad.Count; i++) { if (bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i) hsh1["BinarySearch"] = "(Object)"; } hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)"; } catch (NotSupportedException) { } catch (Exception ex) { hsh1["BinarySearch"] = ex.GetType().Name; } try { for (int i = 0; i < bad.Count; i++) { if (bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i) hsh1["BinarySearch"] = "(Object)"; } hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)"; } catch (NotSupportedException) { } catch (Exception ex) { hsh1["BinarySearch"] = ex.GetType().Name; } good.Clear(); for (int i = 0; i < 100; i++) good.Add(i); Queue que = new Queue(); for (int i = 0; i < 100; i++) que.Enqueue(i + 5000); try { bad.SetRange(0, que); hsh1["Sort"] = "Copy - int, int, IComparer"; } catch (NotSupportedException) { } catch (Exception) { hsh1["Sort"] = "Copy_ExceptionType"; } } //Modifiable methods if (!hsh1.ContainsKey("IsReadOnly") && !hsh1.ContainsKey("Fixed")) { good.Clear(); for (int i = 0; i < 100; i++) good.Add(i); Queue que = new Queue(); for (int i = 0; i < 100; i++) que.Enqueue(i + 5000); bad.InsertRange(0, que); for (int i = 0; i < 100; i++) { if ((int)bad[i] != i + 5000) { hsh1["InsertRange"] = i; } } //AddRange() que = new Queue(); for (int i = 0; i < 100; i++) que.Enqueue(i + 2222); bad.AddRange(que); for (int i = bad.Count - 100; i < bad.Count; i++) { if ((int)bad[i] != (i - (bad.Count - 100)) + 2222) { hsh1["AddRange"] = i + " " + (int)bad[i]; } } bad.RemoveRange(0, que.Count); for (int i = 0; i < 100; i++) { if ((int)bad[i] != i) { hsh1["RemoveRange"] = i + " " + (int)bad[i]; } } //Capacity try { bad.Capacity = bad.Capacity * 2; } catch (Exception ex) { hsh1["Capacity"] = ex.GetType().Name; } try { bad.Capacity = -1; hsh1["Capacity"] = "No_Exception_Thrown, -1"; } catch (ArgumentException) { } catch (Exception ex) { hsh1["Capacity"] = ex.GetType().Name; } int iMakeSureThisDoesNotCause = 0; while (bad.Capacity == bad.Count) { if (iMakeSureThisDoesNotCause++ > 100) break; bad.Add(bad.Count); } if (iMakeSureThisDoesNotCause > 100) hsh1["TrimToSize"] = "Monekeyed, " + bad.Count + " " + bad.Capacity; //TrimToSize() try { bad.TrimToSize(); if (bad.Capacity != bad.Count) { hsh1["TrimToSize"] = "Problems baby"; } } catch (Exception ex) { hsh1["TrimToSize"] = ex.GetType().Name; } } else { Queue que = new Queue(); for (int i = 0; i < 100; i++) que.Enqueue(i + 5000); try { bad.AddRange(que); hsh1["AddRange"] = "Copy"; } catch (NotSupportedException) { } catch (Exception) { hsh1["AddRange"] = "Copy_ExceptionType"; } try { bad.InsertRange(0, que); hsh1["InsertRange"] = "Copy"; } catch (NotSupportedException) { } catch (Exception) { hsh1["InsertRange"] = "Copy_ExceptionType"; } good.Clear(); for (int i = 0; i < 10; i++) good.Add(i); try { bad.RemoveRange(0, 10); hsh1["RemoveRange"] = "Copy"; } catch (NotSupportedException) { } catch (Exception ex) { hsh1["RemoveRange"] = "Copy_ExceptionType, " + ex.GetType().Name; } try { bad.Capacity = bad.Capacity * 2; hsh1["Capacity"] = "No_Exception_Thrown, bad.Capacity*2"; } catch (NotSupportedException) { } catch (Exception ex) { hsh1["Capacity"] = ex.GetType().Name; } try { bad.TrimToSize(); hsh1["TrimToSize"] = "No_Exception_Thrown"; } catch (NotSupportedException) { } catch (Exception ex) { hsh1["TrimToSize"] = ex.GetType().Name; } } }
/// <summary> /// 各种集合的一般用法 /// </summary> /// <param name="args"></param> static void Main(string[] args) { #region Arraylist的一般用法 //需要引用System.Collections的命名空间 /* * ArrayList是动态数组,而Array是静态数组 * 动态的增加和减少元素 * 动态的访问元素支持多种数据类型的同时存储 * 实现了ICollection和IList接口 * 支持自动改变大小的功能 */ //定义一个ArrayList的集合类 ArrayList arraylist = new ArrayList(); //集合的末尾添加元素;Add() arraylist.Add(1); //集合的指定位置插入元素:Insert();会把原来位置上的元素的索引值加一 arraylist.Insert(1, "我们"); arraylist.Insert(0, 2); //遍历集合中的元素:foreach foreach (Object o in arraylist) { Console.WriteLine(o.ToString()); } Console.WriteLine("-------------------"); //定义一个新的集合 ArrayList arraylist1 = new ArrayList(); //新的集合里面插入元素 arraylist1.Insert(0, 3); //将其他的集合增加到新集合的末尾 arraylist1.AddRange(arraylist); //将其他的集合插入到指定位置 arraylist1.InsertRange(4, arraylist); //遍历集合 foreach (Object o in arraylist1) { Console.WriteLine(o.ToString()); } //获得元素xx第一次出现的索引位置 int index = arraylist1.IndexOf("3"); Console.WriteLine(index); //将数组元素移除 arraylist1.Remove(1); //将其他的集合复制到新集合的某一范围上 arraylist1.SetRange(1, arraylist); //获取新集合的某个子集合 ArrayList arraylistNew = arraylist1.GetRange(2, 3); //遍历子集合 foreach (Object o in arraylistNew) { Console.WriteLine(o.ToString()); } Console.WriteLine("------------------"); //定义一个int类型的集合 ArrayList arraylistInt = new ArrayList(); //添加元素 arraylistInt.Add(3); arraylistInt.Add(2); arraylistInt.Add(1); //数组排序 arraylistInt.Sort(); //遍历集合 foreach (Object o in arraylistInt) { Console.WriteLine(o.ToString()); } //集合中是有否包含此内容的元素 Console.WriteLine(arraylistInt.Contains("1")); //清空集合 arraylistInt.Clear(); Console.WriteLine("--------------"); //此外集合还有的方法是: /* * Reserve() 将集合或其中一部分的元素进行发转 * CopyTo() 将集合或其中一部分元素复制到集合中去 * ToArray() 将集合中的元素复制到新的集合中去 */ #endregion #region HashTable的一般用法 /* * HashTable是一个键/值对集合,也可以认为是一种字典集合,它的数据是通过键和值来组织的。 * HashTable可以被称为散列表或者哈希表 * 可通过键来找到相应的值 * 常用属性:Count:键值对数量 * Keys:获取或设置HashTable中键的集合 * Values:获取或设置HashTable中值的集合 * 常用方法:Add() 添加 * Clear() 移除 * Clone() 浅表副本 * Contains() 包含特定的键 * ContainsKey() 包含特定的键 * ContainsValue() 包含特定的值 * CopyTo() 复制到指定索引位置 * Remove() 移除特定键的元素 */ //定义一个HashTable类型的集合 Hashtable hashtable = new Hashtable(); //向集合中添加元素 hashtable.Add("1", 1); hashtable.Add("2", 2); //查看是否包含特定的键 Console.WriteLine(hashtable.ContainsKey("1")); //遍历集合;hashtable.Values代表集合中值的集合 foreach (int e in hashtable.Values) { Console.WriteLine(e); } //遍历集合:使用DictionaryEntry foreach (DictionaryEntry iterm in hashtable) { Console.WriteLine(iterm.Value); } #endregion #region SortedList的一般用法 /* * SortedList是混合性的集合,他也是表示键值对的集合,兼顾了ArrayList和HashTable的优点,不仅可以按照索引访问元素,也可以通过键名来访问元素 * 由于SortedList中的元素都是经过排序存放的,因此又将其称为排序列表 * 键和值都是顺序排列,和HashTable的区别 * 常用方法:Add() 添加 * Clear() 清除 * Contains() 包含特定的键 * ContainsKey() 包含特定的键 * ContainsValue() 包含特定的值 * CopyTo() 复制到指定索引位置 * IndexOfKey() ..... * IndexOfValue().... * SetByIndexOf() 替换集合中指定索引处的值 * GetByIndexOf() 获取集合中指定索引出的值 * GetByIndex() 获取集合中指定索引处的值 * GetKey() 获取集合中指定索引处的键 * GetKeyList() 获取集合中的键 * GetValueList() 获取集合中的值 * Remove() ...移除指定键 * RemoveAt()..移除指定键 */ //定义一个集合 SortedList list = new SortedList(); //添加元素 list.Add("1", 1); list.Add("2", 2); //遍历元素 for (int i = 0; i < list.Count; ++i) { Console.WriteLine("\t{0}:\t{1}", list.GetKey(i), list.GetByIndex(i)); } Console.WriteLine("-------------"); //遍历元素 foreach (DictionaryEntry iterm in list) { Console.WriteLine(iterm.Value); } #endregion #region Stack的一般用法 /* * 堆栈集合,先进后出 * 常用属性:Count * 常用方法:Clear() * Clone()创建Stack的浅表副本 * CopyTo()从指定集合索引开始将Stack复制到现有的一维数组中 * Peek()返回位于Stack顶部的对象但是不将其移除 * Pop()移除并且返回位于Stack顶部的对象 * Push()将Push()对象插入Stack的顶部 * ToArray()将Stack复制到新集合 */ //定义一个Stack类型的集合 Stack stack = new Stack(); //向集合中添加元素(压栈) stack.Push("jin"); stack.Push("yu"); stack.Push("bao"); //移除顶部元素 stack.Pop(); //遍历循环元素 foreach (string e in stack) { Console.WriteLine(e); } #endregion #region 常用集合类 Queue BitArray /* * 此外还有不常用集合类:Queue(先进先出) * 常用属性: * Count * 常用方法: * Clear() * Contains() * CopyTo() * Dequeue()返回并移除集合开始处元素 * Enqueue()将元素添加到结尾处 * GetEnumerator() * Peek() 返回集合开始处元素 * TrimToSize() 容量设置为集合元素的实际数目 * * BitArray(管理位值的压缩数组,该值表示布尔值) * true表示位值是打开的(1) * false...............(0) */ #endregion }
public void TestArrayListSetRangeOverflow () { ArrayList arrayList = new ArrayList (); arrayList.Add (this); try { arrayList.SetRange (Int32.MaxValue, new ArrayList ()); Fail("Should have thrown an ArgumentOutOfRangeException"); } catch(ArgumentOutOfRangeException e) { } catch(Exception e) { Fail("Should have thrown an ArgumentOutOfRangeException instead of " + e.GetType().Name); } }