/// <summary> /// Inspects the members of the data Table, focusing on the named field. It calculates /// the median of the values in the named field. /// </summary> /// <param name="self"></param> /// <param name="fieldName"></param> /// <returns></returns> public static BoxStatistics GetBoxStatistics(this DataTable self, string fieldName) { DataColumn dc = self.Columns[fieldName]; ArrayList lst = new ArrayList(); foreach (DataRow row in self.Rows) { lst.Add(row[fieldName]); } lst.Sort(); BoxStatistics result = new BoxStatistics(); if (lst.Count % 2 == 0) { if (dc.DataType == typeof(string)) { } // For an even number of items, the mean is the average of the middle two values (after sorting) double high = Convert.ToDouble(lst.Count / 2); double low = Convert.ToDouble(lst.Count / 2 - 1); result.Median = (high + low) / 2; } else { result.Median = lst[(int)Math.Floor(lst.Count / (double)2)]; } return result; }
static void Main(string[] args) { ArrayList list = new ArrayList() ; list.Add(new Person("Jim", 30)); list.Add(new Person("Bob", 25)); list.Add(new Person("Bert", 27)); list.Add(new Person("Ernie", 22)); Console.WriteLine ("Unsorted people: ") ; // Несортированный список людей for (int i = 0; i < list.Count; i++) { Console.WriteLine("{0} ({1})", (list[i] as Person).Name, (list[i] as Person).Age); } Console.WriteLine(); Console.WriteLine("People sorted with default comparer (by age):"); // Список людей, отсортированный (по возрасту) //с помощью метода сравнения по умолчанию list.Sort(); for (int i = 0; i < list.Count; i++) { Console.WriteLine("{0} ({1})", (list[i] as Person).Name, (list[i] as Person).Age); } Console.WriteLine(); Console.WriteLine("People sorted with nondefault comparer (by name):"); // Список людей, отсортированный (по имени) с помощью // метода сравнения не по умолчанию list.Sort(PersonComparerName.Default); for (int i = 0; i < list.Count; i++) { Console.WriteLine("{0} ({1})", (list[i] as Person).Name, (list[i] as Person).Age); } Console.ReadKey(); }
static void Main(string[] args) { ArrayList list = new ArrayList(); list.Add(new Person("Jim", 30)); list.Add(new Person("Bob", 25)); list.Add(new Person("Bert", 27)); list.Add(new Person("Ernie", 22)); Console.WriteLine("Unsorted people:"); for (int i = 0; i < list.Count; i++) { Console.WriteLine("{0} ({1})", (list[i] as Person).Name, (list[i] as Person).Age); } Console.WriteLine(); Console.WriteLine( "People sorted with default comparer (by age):"); list.Sort(); for (int i = 0; i < list.Count; i++) { Console.WriteLine("{0} ({1})",(list[i] as Person).Name, (list[i] as Person).Age); } Console.WriteLine(); Console.WriteLine( "People sorted with nondefault comparer (by name):"); list.Sort(PersonComparerName.Default); for (int i = 0; i < list.Count; i++) { Console.WriteLine("{0} ({1})", (list[i] as Person).Name, (list[i] as Person).Age); } Console.ReadKey(); }
static void Main(string[] args) { Console.WriteLine("Basic Array List Testing:"); ArrayList al = new ArrayList(); al.Add("Hello"); al.Add("World"); al.Add(5); al.Add(new FileStream("deleteme", FileMode.Create)); Console.WriteLine("The array has " + al.Count + " items"); foreach (object o in al) { Console.WriteLine(o.ToString()); } Console.WriteLine("\nRemove, Insert and Sort Testing:"); al = new ArrayList(); al.Add("Hello"); al.Add("World"); al.Add("this"); al.Add("is"); al.Add("a"); al.Add("test"); Console.WriteLine("\nBefore:"); foreach (object s in al) Console.WriteLine(s.ToString()); al.Remove("test"); al.Insert(4, "not"); al.Sort(); Console.WriteLine("\nAfter:"); foreach (object s in al) Console.WriteLine(s.ToString()); al.Sort(new reverseSorter()); Console.WriteLine("\nReversed:"); foreach (object s in al) Console.WriteLine(s.ToString()); al.Reverse(); Console.WriteLine("\nReversed again, different method:"); foreach (object s in al) Console.WriteLine(s.ToString()); Console.WriteLine("\nBinary Search Example:"); al = new ArrayList(); al.AddRange(new string[] { "Hello", "World", "this", "is", "a", "test" }); foreach (object s in al) Console.Write(s + " "); Console.WriteLine("\n\"this\" is at index: " + al.BinarySearch("this")); }
/// <summary> /// 查找知道文件夹下所有数据库的名称集合 /// </summary> /// <param name="strFileName">文件夹名</param> /// <returns>返回数据库名称</returns> public string[] FindAllMDBOfFile(string strFileName) { ArrayList alst = new System.Collections.ArrayList();//建立ArrayList对象 try { string[] files = Directory.GetFiles(strFileName); //得到文件 foreach (string file in files) //循环文件 { string exname = file.Substring(file.LastIndexOf(".") + 1); //得到后缀名 if (".mdb".IndexOf(file.Substring(file.LastIndexOf(".") + 1)) > -1) //如果后缀名为.mdb文件 { FileInfo fi = new FileInfo(file); //建立FileInfo对象 alst.Add(fi.FullName); //把.mdb文件全名加人到FileInfo对象 fi = null; } alst.Sort(); } } catch (Exception ex) { if (ErrorMessage != null) { ErrorMessage(6020004, ex.StackTrace, "[AccessImport:FindAllMDBOfFile]", ex.Message); } return((string[])alst.ToArray(typeof(string))); } return((string[])alst.ToArray(typeof(string)));//把ArrayList转化为string[] }
public static void Ejecutar() { System.Collections.ArrayList lista = new System.Collections.ArrayList() { new Persona() { Nombre = "Ana María" }, new Perro() { Nombre = "Sultán" }, new Persona() { Nombre = "Ana" }, new Persona() { Nombre = "José Carlos" }, new Perro() { Nombre = "Chopper" } }; lista.Sort(new ComparadorLongitudNombre()); //ordena por longitud de Nombre foreach (INombrable n in lista) { Console.WriteLine($"{n.Nombre.Length}: {n.Nombre}"); } }
public void Initialize(bool _includeDrafts) { // get the list of blogs, determine how many items we will be displaying, // and then have that drive the view mode string[] blogIds = BlogSettings.GetBlogIds(); int itemCount = (_includeDrafts ? 1 : 0) + 1 + blogIds.Length; _showLargeIcons = itemCount <= 5; // configure owner draw DrawMode = DrawMode.OwnerDrawFixed; SelectionMode = SelectionMode.One; HorizontalScrollbar = false; IntegralHeight = false; ItemHeight = CalculateItemHeight(_showLargeIcons); // populate list if (_includeDrafts) _draftsIndex = Items.Add(new PostSourceItem(new LocalDraftsPostSource(), this)); _recentPostsIndex = Items.Add(new PostSourceItem(new LocalRecentPostsPostSource(), this)); ArrayList blogs = new ArrayList(); foreach (string blogId in BlogSettings.GetBlogIds()) { blogs.Add(new PostSourceItem(Res.Get(StringId.Blog), new RemoteWeblogBlogPostSource(blogId), this)); } blogs.Sort(); Items.AddRange(blogs.ToArray()); }
/// <summary> /// 调用LottoNumbers方法,来随机选择数字 /// </summary> /// <returns>6 random numbers </returns> private static string LottoNumbers() //static静态方法,方便调用,但效率不高 { ArrayList list = new ArrayList(); //要添加using System.Collections命名空间 Random r = new Random(); for (int i = 0; i < 6; i++) { int lottoInt = r.Next(1, 41); if (list.Contains(lottoInt)) //Contains()方法:判断ArrayList数组中是否存在某个元素 { i--; //若数组中存在该元素,则i自动减1,本次循环不算 } else //数组中不存在该随机数 { list.Add(lottoInt); //把该随机数添加到数组中 } } //把该数组从小到大排列 list.Sort(); //依次把数组中元素赋值给一个变量,并在每个数字用-连接 string lottoNumbers = ""; for (int i = 0; i < list.Count; i++) { lottoNumbers = lottoNumbers + list[i].ToString() + "-"; } return lottoNumbers.Substring(0, lottoNumbers.Length - 1); }
private string _transport = ""; //访问模式 #endregion Fields #region Constructors /// <summary> /// 构造函数 /// 从配置文件中初始化变量 /// </summary> /// <param name="inputPara">通知返回来的参数数组</param> /// <param name="notify_id">验证通知ID</param> /// <param name="partner">合作身份者ID</param> /// <param name="key">安全校验码</param> /// <param name="input_charset">编码格式</param> /// <param name="sign_type">加密类型</param> /// <param name="transport">访问模式</param> public Alipay_Notify(ArrayList inputPara, string notify_id, string partner, string key, string input_charset, string sign_type, string transport) { _transport = transport; if (_transport == "https") { gateway = "https://www.alipay.com/cooperate/gateway.do?"; } else { gateway = "http://notify.alipay.com/trade/notify_query.do?"; } _partner = partner.Trim(); _key = key.Trim(); _input_charset = input_charset; _sign_type = sign_type.ToUpper(); sPara = Alipay_Function.Para_filter(inputPara); //过滤空值、sign与sign_type参数 sPara.Sort(); //得到从字母a到z排序后的加密参数数组 //获得签名结果 mysign = Alipay_Function.Build_mysign(sPara, _key, _sign_type, _input_charset); //获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求 responseTxt = Verify(notify_id); }
public ContextMenu GetContextMenu() { ContextMenu cm = new ContextMenu(); // add items in the same order that we encounter them, visually // iterate through children, looking for Action objects ArrayList al = new ArrayList(); foreach (Control c in Controls) if ((c is Action) || (c is GroupBox)) al.Add(c); // now, sort these by y position al.Sort(this); // now, iterate through them, creating menu items for them foreach (Control c in al) { if (c is Action) { Action ac = (Action)c; MenuItem mi = new MenuItem(ac.Text, new EventHandler(cm_OnMenuClick)); mi.Enabled = ac.Enabled; mi.Tag = ac; cm.MenuItems.Add(mi); } else if (c is GroupBox) cm.MenuItems.Add(new MenuItem("-")); } return cm; }
static void Main(string[] args) { ArrayList a = new ArrayList(); a.Add("Arnold"); a.Add("Smith"); a.Add("Cordiner"); a.Add("Mitchel"); a.Sort(); foreach (string name in a) { System.Console.WriteLine("{0}",name); } printContents(a); // *********** UN-COMMENT THE ABOVE CODE ************ //1) what 'using' statement (namespace) do you need to //add to this code (at the top of the file)to get it to run? // Add it and then step into the program (F11) //2) add code here that uses the Sort method of the ArrayList // to sort into alphabetical order // add code here to display again all names in the //Array List in the console //3) Put the repeated code for displaying the contents // of the ArrayList in a seperate method // make sure that you pass the ArrayList to this method Console.ReadLine(); System.Console.ReadLine(); }
public static int maxBoxes(ArrayList boxes) { int N = boxes.Count; if (N == 0) return 0; IComparer myComparer = new BoxesComparer(); boxes.Sort(0, N, myComparer); int[] dp = new int[N]; int res = 1; for (int i = 0; i < N; ++i) { dp[i] = 1; for (int j = 0; j < i; ++j) { Box myBox_i = (Box)boxes[i]; Box myBox_j = (Box)boxes[j]; if (myBox_i.vol > myBox_j.vol && myBox_i.weight > myBox_j.weight) dp[i] = Math.Max(dp[i], dp[j] + 1); } res = Math.Max(res, dp[i]); } return res; }
public IndexTable(Dictionary<int, string> dict_with_index_paths, List<string> stopwords) { index_row = new ArrayList(); foreach (var item in dict_with_index_paths) { StreamReader reader = new StreamReader(item.Value); string[] words = Regex.Split(reader.ReadToEnd(), @"\W+"); foreach(string word in words) { if (!stopwords.Contains(word) && word.Count() > 1 && word != "") index_row.Add(new Index(word.ToLower(), 1, item.Key.ToString())); } } IndexCompareWords sort_index = new IndexCompareWords(); index_row.Sort(sort_index); foreach(string duplicate in findDuplicates(index_row)) { reduceDuplicateAndUpdateIndexTable(index_row, duplicate); } saveIndexTableToDisk(index_row); }
/// <summary> /// /// </summary> /// <param name="container"></param> /// <returns></returns> protected override object[] GetControls(IContainer container) { ComponentCollection components = container.Components; ArrayList controls = new ArrayList(); foreach (IComponent component in components) { if (component is System.Web.UI.Control) { Control c = (Control)component; List<ButtonBase> buttons = ControlUtils.FindControls<ButtonBase>(c); if (buttons != null && buttons.Count > 0) { foreach (ButtonBase btn in buttons) { if (btn.ID.IsNotEmpty() && !controls.Contains(btn.ID)) { controls.Add(btn.ID); } } } } } controls.Sort(Comparer.Default); return controls.ToArray(); }
private IList GetMembers (Type type) { ArrayList members = new ArrayList (); members.AddRange (type.GetMembers (BindingFlags)); members.Sort (NameComparer); return members; }
static void Main( string[] args ) { List<int> l = new List<int>() { 4, 3, 2, 5, 3, 2, 1 }; /* convert the IComparer to Comparison<int> (x,y) => ( new IntSorter() ).Compare( x, y ) is the answer */ l.Sort((x, y) => (new IntSorter()).Compare(x, y)); /* test */ l.ForEach(i => Console.Write(i)); Console.WriteLine(); /* second question */ /* the ArrayList's Sort method accepts ONLY an IComparer */ /* The "old" way */ ArrayList a1 = new ArrayList() { 1, 5, 3, 3, 2, 4, 3 }; a1.Sort(new ComparisonComparer<int>(IntComparer)); for(int i = 0; i < a1.Count; ++i) { Console.Write(a1[i]); } Console.WriteLine(); // The .NET >= 4.5 way ArrayList a2 = new ArrayList() { 1, 5, 3, 3, 2, 4, 3 }; a2.Sort(Comparer<int>.Create(IntComparer)); for(int i = 0; i < a2.Count; ++i) { Console.Write(a2[i]); } Console.ReadLine(); }
static void Main(string[] args) { ArrayList al = new ArrayList(); al.Add(new ShoppinCartItem("Car", 5000)); al.Add(new ShoppinCartItem("Book", 30)); al.Add(new ShoppinCartItem("Phone", 80)); al.Add(new ShoppinCartItem("Computer", 1000)); al.Sort(); foreach(ShoppinCartItem item in al) { Console.WriteLine(item.ItemName + " " + item.Price); } al.Reverse(); foreach(ShoppinCartItem item in al) { Console.WriteLine(item.ItemName + " " + item.Price); } Console.ReadKey(); }
// ---------------------------------------- /// <summary> /// Finding all ancestors (all boxes box) with given box type in Ferda Archive tree structure /// </summary> /// <param name="Box">Box in archive, for which function searches the ancestors</param> /// <param name="ID">type of searched boxes (string identifier)</param> /// <returns></returns> public static IBoxModule[] ListAncestBoxesWithID(IBoxModule Box, string ID) { ArrayList MyBoxes = new ArrayList(); IBoxModule[] Ancestors = Box.ConnectionsFrom().ToArray(); foreach (IBoxModule b in Ancestors) { if (b.MadeInCreator.Identifier == ID) // this ancestor has desired type MyBoxes.Add(b); else // ancestor doesn't have desired type. Further we searche among it's ancestors (recurse) { IBoxModule[] b_ancestors = ListAncestBoxesWithID(b, ID); // recurse foreach (IBoxModule bb in b_ancestors) MyBoxes.Add(bb); } } // eliminating the duplicites MyBoxes.Sort(); IBoxModule[] SortedBoxes = (IBoxModule[])MyBoxes.ToArray(typeof(IBoxModule)); ArrayList MyUniqueBoxes = new ArrayList(); foreach (IBoxModule bbb in SortedBoxes) { if (MyUniqueBoxes.BinarySearch(bbb) < 0) MyUniqueBoxes.Add(bbb); } IBoxModule[] resultArray = (IBoxModule[])MyUniqueBoxes.ToArray(typeof(IBoxModule)); return resultArray; }
private void PrivateTestSort(ArrayList arrayList) { Random random = new Random(1027); // Sort arrays of lengths up to 200 for (int i = 1; i < 200; i++) { for (int j = 0; j < i; j++) { arrayList.Add(random.Next(0, 1000)); } arrayList.Sort(); for (int j = 1; j < i; j++) { if ((int)arrayList[j] < (int)arrayList[j - 1]) { Assert.Fail("ArrayList.Sort()"); return; } } arrayList.Clear(); } }
public override string BuildNumber(int Num) //id = 21 { System.Random rd = new Random(); StringBuilder sb = new StringBuilder(); ArrayList al = new ArrayList(); for (int i = 0; i < Num; i++) { al.Clear(); for (int j = 0; j < 5; j++) { int Ball = 0; while ((Ball == 0) || isExistBall(al, Ball)) Ball = rd.Next(1, 15 + 1); al.Add(Ball.ToString().PadLeft(2, '0')); } CompareToAscii compare = new CompareToAscii(); al.Sort(compare); string LotteryNumber = ""; for (int j = 0; j < al.Count; j++) LotteryNumber += al[j].ToString() + " "; sb.Append(LotteryNumber.Trim() + "\n"); } string Result = sb.ToString(); Result = Result.Substring(0, Result.Length - 1); return Result; }
public static PropertyDescriptorCollection GetMethodProperties( object obj ) { System.Type type = obj.GetType(); if ( obj is MethodPropertyDescriptor.MethodPropertyValueHolder ) { MethodPropertyDescriptor.MethodPropertyValueHolder mobj = obj as MethodPropertyDescriptor.MethodPropertyValueHolder; // if ( mobj.Method.IsVoidMethdod ) // return null; return mobj.Method.GetChildProperties( null, null ); } MethodInfo[] methods = type.GetMethods ( BindingFlags.Instance|BindingFlags.InvokeMethod|BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.FlattenHierarchy ); ArrayList methodDesc = new ArrayList(); for ( int i = 0; i < methods.Length; i++ ) { MethodInfo method = methods[i]; if ( /*method.IsPublic &&*/ !method.IsSpecialName ) { methodDesc.Add( new MethodPropertyDescriptor( obj, method ) ); } } methodDesc.Sort( new MethodNameComparer() ); MethodPropertyDescriptor[] methodsDesc = (MethodPropertyDescriptor[])methodDesc.ToArray ( typeof(MethodPropertyDescriptor)); return new PropertyDescriptorCollection(methodsDesc); }
public override void execute3(RunTimeValueBase thisObj,FunctionDefine functionDefine,SLOT returnSlot,SourceToken token,StackFrame stackframe,out bool success) { System.Collections.ArrayList arraylist = (System.Collections.ArrayList)((LinkObj <object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value; try { arraylist.Sort(); returnSlot.setValue(ASBinCode.rtData.rtUndefined.undefined); success = true; } //catch (KeyNotFoundException) //{ // success = false; // stackframe.throwAneException(token, arraylist.ToString() + "没有链接到脚本"); //} catch (ArgumentException a) { success = false; stackframe.throwAneException(token,a.Message); } catch (IndexOutOfRangeException i) { success = false; stackframe.throwAneException(token,i.Message); } }
public override string BuildNumber(int Num) { Random random = new Random(); StringBuilder builder = new StringBuilder(); ArrayList al = new ArrayList(); for (int i = 0; i < Num; i++) { al.Clear(); for (int j = 0; j < 5; j++) { int ball = 0; while ((ball == 0) || base.isExistBall(al, ball)) { ball = random.Next(1, 0x10); } al.Add(ball.ToString().PadLeft(2, '0')); } LotteryBase.CompareToAscii comparer = new LotteryBase.CompareToAscii(); al.Sort(comparer); string str = ""; for (int k = 0; k < al.Count; k++) { str = str + al[k].ToString() + " "; } builder.Append(str.Trim() + "\n"); } string str2 = builder.ToString(); return str2.Substring(0, str2.Length - 1); }
public static string[] getComPorts() { var list = new ArrayList(); ManagementClass win32_pnpentity = new ManagementClass("Win32_PnPEntity"); ManagementObjectCollection col = win32_pnpentity.GetInstances(); Regex reg = new Regex(".+\\((?<port>COM\\d+)\\)"); foreach (ManagementObject obj in col) { // name : "USB Serial Port(COM??)" string name = (string)obj.GetPropertyValue("name"); if (name != null && name.Contains("(COM")) { // "USB Serial Port(COM??)" -> COM?? Match m = reg.Match(name); string port = m.Groups["port"].Value; // description : "USB Serial Port" string desc = (string)obj.GetPropertyValue("Description"); // result string : "COM?? (USB Serial Port)" list.Add(port + " (" + desc + ")"); } } ComPortComparer comp = new ComPortComparer(); list.Sort(comp); return (string[])list.ToArray(typeof(string)); }
public int winner(string[] votes) { int ret = -1; int soFar = int.MaxValue; ArrayList val = new ArrayList(); for (int j = 0; j < votes[0].Length; j++) { int c = 0; for (int i = 0; i < votes.Length; i++) { c += (votes[i][j] - 'a'); } val.Add(c); if (soFar > c) { soFar = c; ret = j; } } val.Sort(); if (val.Count > 1 && (int)val[1] == soFar) return -1; return ret; }
public override string BuildNumber(int Num, int Type)// Type: 8 = 选8,7 = 选7,6 = 选6,5 = 选5, 4 = 选4,3 = 选3,2 = 选2,1 = 选1 { if ((Type != 8) && (Type != 7) && (Type != 6) && (Type != 5) && (Type != 4) && (Type != 3) && (Type != 2) && (Type != 1)) Type = 8; System.Random rd = new Random(); StringBuilder sb = new StringBuilder(); ArrayList al = new ArrayList(); for (int i = 0; i < Num; i++) { string LotteryNumber = ""; for (int j = 0; j < Type; j++) { int Ball = 0; while ((Ball == 0) || isExistBall(al, Ball)) Ball = rd.Next(1, 80 + 1); al.Add(Ball.ToString().PadLeft(2, '0')); } CompareToAscii compare = new CompareToAscii(); al.Sort(compare); for (int j = 0; j < al.Count; j++) LotteryNumber += al[j].ToString() + " "; sb.Append(LotteryNumber.Trim() + "\n"); } string Result = sb.ToString(); Result = Result.Substring(0, Result.Length - 1); return Result; }
public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt ,ref string sMsgSignature) { ArrayList AL = new ArrayList(); AL.Add(sToken); AL.Add(sTimeStamp); AL.Add(sNonce); AL.Add(sMsgEncrypt); AL.Sort(new DictionarySort()); string raw = ""; for (int i = 0; i < AL.Count; ++i) { raw += AL[i]; } SHA1 sha; ASCIIEncoding enc; string hash = ""; try { sha = new SHA1CryptoServiceProvider(); enc = new ASCIIEncoding(); byte[] dataToHash = enc.GetBytes(raw); byte[] dataHashed = sha.ComputeHash(dataToHash); hash = BitConverter.ToString(dataHashed).Replace("-", ""); hash = hash.ToLower(); } catch (Exception) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error; } sMsgSignature = hash; return 0; }
/// <summary> /// Obtiene el mínimo entre tres numeros, siempre y cuando sea mayor que -1 /// </summary> /// <param name="n1">Número 1</param> /// <param name="n2">Número 2</param> /// <param name="n3">Número 3</param> /// <returns>Menor número que sea mayor que -1</returns> public int minimo(int n1, int n2, int n3) { System.Collections.ArrayList numeros = new System.Collections.ArrayList(); if (n1 > -1) { numeros.Add(n1); } if (n2 > -1) { numeros.Add(n2); } if (n3 > -1) { numeros.Add(n3); } if (numeros.Count > 0) { numeros.Sort(); return((int)numeros[0]); } else { return(-1); } }
public override void SaveSettings() { if (!this.writeable) throw new InvalidOperationException("Attempted to write to a non-writeable Settings Storage"); string dirPath = Path.GetDirectoryName( filePath ); if ( !Directory.Exists( dirPath ) ) Directory.CreateDirectory( dirPath ); XmlTextWriter writer = new XmlTextWriter( filePath, System.Text.Encoding.UTF8 ); writer.Formatting = Formatting.Indented; writer.WriteProcessingInstruction( "xml", "version=\"1.0\"" ); writer.WriteStartElement( "NUnitSettings" ); writer.WriteStartElement( "Settings" ); ArrayList keys = new ArrayList( settings.Keys ); keys.Sort(); foreach( string name in keys ) { object val = settings[name]; if ( val != null ) { writer.WriteStartElement( "Setting"); writer.WriteAttributeString( "name", name ); writer.WriteAttributeString( "value", val.ToString() ); writer.WriteEndElement(); } } writer.WriteEndElement(); writer.WriteEndElement(); writer.Close(); }
/// <summary> /// Allows for custom initialization based on type. This will only be called once /// for each type passed to the contributor. /// </summary> /// <param name="type">The type.</param> protected override void Initialize(Type type) { ArrayList problematicMethods = new ArrayList(); ArrayList validationMeta = new ArrayList(); foreach (MethodInfo methodInfo in type.GetMethods(PublicBinding)) { if (!methodInfo.IsDefined(typeof(ValidateSelfAttribute), true)) continue; ValidateSelfAttribute[] attrs = (ValidateSelfAttribute[]) methodInfo.GetCustomAttributes(typeof (ValidateSelfAttribute), true); ValidateSelfAttribute validateSelf = attrs[0]; ParameterInfo[] parameters = methodInfo.GetParameters(); if (IsValidSelfValidationMethod(parameters)) problematicMethods.Add(methodInfo.Name); else validationMeta.Add(new SelfValidationMeta(methodInfo, validateSelf.RunWhen, validateSelf.ExecutionOrder)); } if (problematicMethods.Count == 0) { validationMeta.Sort(SelfValidationMetaComparer.Instance); methodsPerType.Add(type, validationMeta); return; } ThrowErrorForInvalidSignatures(type, problematicMethods); }
/// <devdoc> /// Returns a list of all control IDs in the container. /// </devdoc> private string[] GetControls(IDesignerHost host, object instance) { IContainer container = host.Container; // Locate nearest container IComponent component = instance as IComponent; if (component != null && component.Site != null) { container = component.Site.Container; } if (container == null) { return null; } ComponentCollection allComponents = container.Components; ArrayList array = new ArrayList(); // For each control in the container foreach (IComponent comp in (IEnumerable)allComponents) { Control control = comp as Control; // Ignore DesignerHost.RootComponent (Page or UserControl), controls that don't have ID's, // and the Control itself if (control != null && control != instance && control != host.RootComponent && control.ID != null && control.ID.Length > 0 && FilterControl(control)) { array.Add(control.ID); } } array.Sort(Comparer.Default); return (string[])array.ToArray(typeof(string)); }
/** 获取带参数的请求URL @return String */ public virtual string getRequestURL() { this.createSign(); StringBuilder sb = new StringBuilder(); ArrayList akeys=new ArrayList(parameters.Keys); akeys.Sort(); foreach(string k in akeys) { string v = (string)parameters[k]; if (null != v && "key".CompareTo(k) != 0 && "spbill_create_ip".CompareTo(k)!=0) { sb.Append(k + "=" + TenpayUtil.UrlEncode(v, getCharset()) + "&"); } else if("spbill_create_ip".CompareTo(k) == 0){ sb.Append(k + "=" + v.Replace(".", "%2E") + "&"); } } //去掉最后一个& if(sb.Length > 0) { sb.Remove(sb.Length-1, 1); } return this.getGateUrl() + "?" + sb.ToString(); }
private static IList findAllFromChild( IList parents, ObjectInfo state ) { ArrayList results = new ArrayList(); foreach (EntityInfo info in state.EntityInfo.ChildEntityList) { ObjectInfo childState = new ObjectInfo( info); childState.includeAll(); IList children = ObjectDb.FindAll( childState ); for (int i = 0; i < children.Count; i++) { IEntity child = children[i] as IEntity; // state //child.state.Order = state.Order; results.Add( child ); parents.RemoveAt( Query.getIndexOfObject( parents, child ) ); } } if (parents.Count > 0) results.AddRange( parents ); results.Sort(); return results; }
//����sha1ǩ�� public string createSHA1Sign() { StringBuilder sb = new StringBuilder(); ArrayList akeys = new ArrayList(parameters.Keys); akeys.Sort(); foreach (string k in akeys) { string v = (string)parameters[k]; if (null != v && "".CompareTo(v) != 0 && "sign".CompareTo(k) != 0 && "key".CompareTo(k) != 0) { if (sb.Length == 0) { sb.Append(k + "=" + v); } else { sb.Append("&" + k + "=" + v); } } } string paySign = SHA1Util.getSha1(sb.ToString()).ToString().ToLower(); //debug��Ϣ this.setDebugInfo(sb.ToString() + " => sign:" + paySign); return paySign; }
private bool SortArray(System.Collections.ArrayList vettore) { bool result = false; vettore.Sort(); result = true; return(result); }
public static void SortToolStripItemCollection(ToolStripItemCollection coll) { System.Collections.ArrayList oAList = new System.Collections.ArrayList(coll); oAList.Sort(new ToolStripItemComparer()); coll.Clear(); foreach (ToolStripItem oItem in oAList) { coll.Add(oItem); } }
static void Main(string[] args) { System.Collections.ArrayList a = new System.Collections.ArrayList(); Random r = new Random(); PrintValues(a); for (int i = 0; i < 10; i++) { a.Add(r.Next(100)); } PrintValues(a); a.Sort(); PrintValues(a); a.RemoveAt(3); PrintValues(a); }
public override string ToString() { System.Text.StringBuilder ret = new System.Text.StringBuilder(); ret.Append("Proved: "); foreach (Statement s in Proved) { ret.Append(s.ToString()); } ret.Append("\n"); foreach (ProofStep step in Steps) { ret.Append("\t"); ret.Append(step.Rule.ToString()); ret.Append("\n"); System.Collections.ArrayList vars = new System.Collections.ArrayList(step.Substitutions.Keys); vars.Sort(); foreach (Variable v in vars) { ret.Append("\t\t"); ret.Append(v); ret.Append(" => "); ret.Append(step.Substitutions[v]); ret.Append("\n"); } if (vars.Count > 0) { foreach (Statement s in step.Rule.Consequent) { Statement ss = s; foreach (Variable v in vars) { ss = ss.Replace(v, (Resource)step.Substitutions[v]); } ret.Append("\t\t=> "); ret.Append(ss.ToString()); ret.Append("\n"); } } } return(ret.ToString()); }
/// <summary> /// Retrieves an array of strings that contains all the subkey names. /// </summary> /// <returns>An array of strings that contains the names of the subkeys for the current key.</returns> /// <exception cref="System.ObjectDisposedException">The RegistryKey being manipulated is closed (closed keys cannot be accessed).</exception> public string[] GetSubKeyNames() { if (CheckHKey()) { //error/success returned by RegKeyEnumEx int result = 0; //store the names System.Collections.ArrayList subkeynames = new System.Collections.ArrayList(); int index = 0; //buffer to store the name char[] buffer = new char[256]; int keynamelen = buffer.Length; //enumerate sub keys result = RegEnumKeyEx(m_handle, index, buffer, ref keynamelen, 0, null, 0, 0); //while there are more key names available while (result != ERROR_NO_MORE_ITEMS) { //add the name to the arraylist subkeynames.Add(new string(buffer, 0, keynamelen)); //increment index index++; //reset length available to max keynamelen = buffer.Length; //retrieve next key name result = RegEnumKeyEx(m_handle, index, buffer, ref keynamelen, 0, null, 0, 0); } //sort the results subkeynames.Sort(); //return a fixed size string array return((string[])subkeynames.ToArray(typeof(string))); } else { throw new ObjectDisposedException("The RegistryKey being manipulated is closed (closed keys cannot be accessed)."); } }
static void Main(string[] args) { System.Collections.ArrayList list = new System.Collections.ArrayList(); list.Add("World"); list.Add("Hello"); Console.WriteLine("Count {0}", list.Count); Console.WriteLine("Capacity {0}", list.Capacity); //can set capacuty when list is created also list.Sort(); PrintCollections(list); Console.WriteLine("list[0] = {0}", list[0]); Console.WriteLine("list[1] = {0}", list[1]); Console.WriteLine("Contains Hello {0}", list.Contains("Hello")); //must walk through each item in the array to do a comparison list.BinarySearch("Hello"); //list must be sorted first, much faster than contains search }
private System.ComponentModel.TypeConverter.StandardValuesCollection GetCachedStandardValues(System.ComponentModel.ITypeDescriptorContext context) { if (_StandardValues == null) { FriendlyNameToInstanceDescriptorMap = new System.Collections.Hashtable(); System.Collections.ArrayList arrayList = new System.Collections.ArrayList(); arrayList.Add(DefaultRenderer); FriendlyNameToInstanceDescriptorMap["(Default)"] = CreateInstanceDescriptor(DefaultRenderer); System.Type[] typeArr = RendererType.Assembly.GetExportedTypes(); for (int i = 0; i < typeArr.Length; i++) { System.Type type = typeArr[i]; if (((type == RendererType) || type.IsSubclassOf(RendererType)) && !type.IsAbstract) { string s = Skybound.ComponentModel.DisplayNameAttribute.GetFriendlyName(type); FriendlyNameToInstanceDescriptorMap[s] = new System.ComponentModel.Design.Serialization.InstanceDescriptor(type.GetConstructor(System.Type.EmptyTypes), null, true); arrayList.Add(System.Activator.CreateInstance(type, null)); } } arrayList.Sort(this); _StandardValues = new System.ComponentModel.TypeConverter.StandardValuesCollection(arrayList); } return(_StandardValues); }
/// <summary> /// Obtain the minimum element of the given collection with the specified comparator. /// </summary> /// <param name="Collection">Collection from which the minimum value will be obtained.</param> /// <param name="Comparator">The comparator with which to determine the minimum element.</param> /// <returns></returns> public static System.Object Min(System.Collections.ICollection Collection, System.Collections.IComparer Comparator) { System.Collections.ArrayList tempArrayList; if (((System.Collections.ArrayList)Collection).IsReadOnly) { throw new System.NotSupportedException(); } if ((Comparator == null) || (Comparator is System.Collections.Comparer)) { try { tempArrayList = new System.Collections.ArrayList(Collection); tempArrayList.Sort(); } catch (System.InvalidOperationException e) { throw new System.InvalidCastException(e.Message); } return((System.Object)tempArrayList[0]); } else { try { tempArrayList = new System.Collections.ArrayList(Collection); tempArrayList.Sort(Comparator); } catch (System.InvalidOperationException e) { throw new System.InvalidCastException(e.Message); } return((System.Object)tempArrayList[0]); } }
private void Current_RenderFrame_Sort(object sender, EventArgs e) { try { if (CURRENT_STATE == State.IDLE) { CoreManager.Current.RenderFrame -= new EventHandler <EventArgs>(Current_RenderFrame_Sort); } else if (CURRENT_STATE == State.INITIATED) { bool identifying = false; MainView.prgProgressBar.Max = sortList.Count; MainView.prgProgressBar.PreText = "identifying..."; foreach (WorldObject obj in sortList) { if (!obj.HasIdData) { identifying = true; MainView.prgProgressBar.Position = sortList.IndexOf(obj) + 1; break; } } if (!identifying) { CURRENT_STATE = State.BUILDING_LIST; MainView.prgProgressBar.Position = MainView.prgProgressBar.Max; } } else if (CURRENT_STATE == State.BUILDING_LIST) { String[] sortKeys = MainView.edtSortString.Text.Split(','); System.Collections.ArrayList sortValueList = new System.Collections.ArrayList(); for (int i = sortKeys.Length - 1; i >= 0; i--) { foreach (WorldObject worldObject in sortList) { SortFlag sf = SortFlag.decode(sortKeys[i]); String sortMetric = sf.valueOf(worldObject); if (!sortValueList.Contains(sortMetric)) { sortValueList.Add(sortMetric); } } sortValueList.Sort(new AlphanumComparator()); System.Collections.ArrayList newSortList = new System.Collections.ArrayList(); if (!(sortKeys[i].Length == 3 && sortKeys[i].Substring(2, 1).Equals("-"))) { sortValueList.Reverse(); } foreach (Object sortValue in sortValueList) { foreach (WorldObject worldObject in sortList) { String sortMetric = SortFlag.decode(sortKeys[i]).valueOf(worldObject); if (sortMetric.Equals(sortValue)) { newSortList.Add(worldObject); } } } sortList = newSortList; if (i == 0) { if (Properties.Settings.Default.ReverseSortList) { sortList.Reverse(); } foreach (WorldObject worldObject in sortList) { sortQueue.Enqueue(worldObject); } } } Util.WriteToChat(sortQueue.Count + " items in queue..."); CURRENT_STATE = State.MOVING_ITEMS; MainView.prgProgressBar.PreText = "working..."; MainView.prgProgressBar.Max = sortQueue.Count; } else if (CURRENT_STATE == State.MOVING_ITEMS) { if (sortQueue.Count > 0) { if (Core.Actions.BusyState == 0) { MainView.prgProgressBar.Position = MainView.prgProgressBar.Max - sortQueue.Count; WorldObject obj = (WorldObject)sortQueue.Dequeue(); if (containerDest != Core.CharacterFilter.Id && Core.WorldFilter[containerDest].ObjectClass.Equals(ObjectClass.Player)) { Globals.Host.Actions.GiveItem(obj.Id, containerDest); } else { Globals.Host.Actions.MoveItem(obj.Id, containerDest, containerDestSlot, true); } } } else { CURRENT_STATE = State.IDLE; MainView.prgProgressBar.PreText = "done!"; MainView.prgProgressBar.Position = MainView.prgProgressBar.Max; MainView.btnActivate.Text = "Activate"; Util.WriteToChat("done sorting items!"); } } } catch (Exception ex) { Util.LogError(ex); } }
public void AddAllData(System.Collections.ArrayList alData) { if (alData.Count <= 0) { return; } #region 患者信息赋值 Neusoft.HISFC.Models.Pharmacy.ApplyOut tempApply = alData[0] as Neusoft.HISFC.Models.Pharmacy.ApplyOut; string clinicNO = tempApply.PatientNO; Neusoft.HISFC.BizLogic.Registration.Register registerManager = new Neusoft.HISFC.BizLogic.Registration.Register(); Neusoft.HISFC.Models.Registration.Register register = registerManager.GetByClinic(clinicNO); foreach (Neusoft.HISFC.Models.Pharmacy.ApplyOut temp in alData) { temp.UseTime = temp.Operation.ApplyOper.OperTime; temp.PatientNO = register.PID.CardNO; temp.User02 = register.Name; } #endregion if (this.ucInject == null) { this.ucInject = new ucZLInjectList(); } this.ucInject.AddAllData(alData); //对打印标签的情况 对数据按组合分组 ComboSort comboSort = new ComboSort(); alData.Sort(comboSort); ArrayList alGroupApplyOut = new ArrayList(); ArrayList alCombo = new ArrayList(); string privCombo = "-1"; #region 标签打印 foreach (Neusoft.HISFC.Models.Pharmacy.ApplyOut info in alData) { if (privCombo == "-1" || (privCombo == info.CombNO && info.CombNO != "")) { alCombo.Add(info.Clone()); privCombo = info.CombNO; continue; } else //不同处方号 { alGroupApplyOut.Add(alCombo); privCombo = info.CombNO; alCombo = new ArrayList(); alCombo.Add(info.Clone()); } } if (alCombo.Count > 0) { alGroupApplyOut.Add(alCombo); } this.alGroupCompound = alGroupApplyOut; #endregion }
/// <summary> /// 对药品申请数据按照项目编码排序 /// </summary> /// <param name="alApplyOut"></param> public static void SortApplyOutByItemCode(ref System.Collections.ArrayList alApplyOut) { CompareApplyOutByItemCode compareInstance = new CompareApplyOutByItemCode(); alApplyOut.Sort(compareInstance); }
public void Sort(IComparer compare) { list.Sort(compare); Reload(); }