Sort() public method

public Sort ( ) : void
return void
 /// <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;
 }
Example #2
0
        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();
        }
Example #3
0
 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(); 
 }
Example #4
0
        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"));
        }
		/** 获取带参数的请求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();
		}
Example #6
0
            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;
            }
Example #7
0
 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);
 }
        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();
        }
Example #9
0
        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;
        }
Example #10
0
        //����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;
        }
        /// <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();
        }
Example #12
0
        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 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());
        }
Example #14
0
        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;
        }
		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 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();
		}
Example #17
0
        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;
        }
Example #18
0
		private IList GetMembers (Type type)
		{
			ArrayList members = new ArrayList ();
			members.AddRange (type.GetMembers (BindingFlags));
			members.Sort (NameComparer);
			return members;
		}
Example #19
0
        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;
        }
Example #20
0
            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 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);
        }
Example #22
0
        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;
        }
        // ----------------------------------------
        /// <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;
        }
Example #24
0
        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();
        }
Example #25
0
		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);
		}
        /// <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));
        }
Example #27
0
 /// <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);
 }
Example #28
0
        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));
        }
		/// <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);
		}
        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();
        }