当前位置: 首页>>代码示例>>C#>>正文


C# SortedList.GetKey方法代码示例

本文整理汇总了C#中System.Collections.SortedList.GetKey方法的典型用法代码示例。如果您正苦于以下问题:C# SortedList.GetKey方法的具体用法?C# SortedList.GetKey怎么用?C# SortedList.GetKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Collections.SortedList的用法示例。


在下文中一共展示了SortedList.GetKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            SortedList traductor = new SortedList();
            traductor.Add("{", "begin");
            traductor.Add("}", "begin");
            traductor.Add("WriteLine", "WriteLn");
            traductor.Add("ReadLine", "ReadLn");
            traductor.Add("void", "procedure");
            traductor.Add("Console", "");

            //StreamReader fichero_origen;
            //fichero_origen = File.OpenText("prueba.cs");
            List<string> lista = File.ReadAllLines("prueba.cs").ToList();
            //fichero_origen.Close();
            string itemaux = "";
            foreach (string item in lista)
            {
                itemaux = item;
                for (int i = 0; i < traductor.Count; i++)
                {
                    if (item.Contains(traductor.GetKey(i).ToString()))
                        itemaux = item.Replace(traductor.GetKey(i).ToString(), traductor.GetByIndex(i).ToString());
                }
                Console.WriteLine(itemaux);
            }
        }
开发者ID:ruarrimactire,项目名称:Hodei,代码行数:26,代码来源:Program.cs

示例2: VisitDocumentElements

    internal override void VisitDocumentElements(DocumentElements elements)
    {
      SortedList splitParaList = new SortedList();

      for (int idx = 0; idx < elements.Count; ++idx)
      {
        Paragraph paragraph = elements[idx] as Paragraph;
        if (paragraph != null)
        {
          Paragraph[] paragraphs = paragraph.SplitOnParaBreak();
          if (paragraphs != null)
            splitParaList.Add(idx, paragraphs);
        }
      }

      int insertedObjects = 0;
      for (int idx = 0; idx < splitParaList.Count; ++idx)
      {
        int insertPosition = (int)splitParaList.GetKey(idx);
        Paragraph[] paragraphs = (Paragraph[])splitParaList.GetByIndex(idx);
        foreach (Paragraph paragraph in paragraphs)
        {
          elements.InsertObject(insertPosition + insertedObjects, paragraph);
          ++insertedObjects;
        }
        elements.RemoveObjectAt(insertPosition + insertedObjects);
        --insertedObjects;
      }
    }
开发者ID:GorelH,项目名称:PdfSharp,代码行数:29,代码来源:PdfFlattenVisitor.cs

示例3: KthSmallest

 // use a max heap (priority queue) of size k
 // (C# doesn't provide priority queue, use SortedList instead)
 public static int KthSmallest(int[] a, int k)
 {
     SortedList list = new SortedList();
     int m = a.Length - k + 1;
     for (int i = 0; i < m; i++)
         list.Add(a[i], null);
     for (int i = m; i < a.Length; i++)
     {
         if ((int)list.GetKey(0) < a[i])
         {
             list.RemoveAt(0);
             list.Add(a[i], null);
         }
     }
     return (int)list.GetKey(0);
 }
开发者ID:zhouhufeng,项目名称:Algo,代码行数:18,代码来源:ArraysAlgo.cs

示例4: Main

        /// <summary>
        /// The main entry point of the application - does all the work, really.
        /// </summary>
        public static void Main()
        {
            SortedList table = new SortedList();
            string fileData = string.Empty;

            Console.WriteLine("This program counts how many times each word occurs in a file.");
            Console.Write("Enter the filename of the file to read from:\n > ");
            string filename = Console.ReadLine();
            while (string.IsNullOrEmpty(filename))
            {
                Console.Write("You cannot enter a blank path name - try again:\n > ");
                filename = Console.ReadLine();
            }

            // Try to access the file and bail out if an error occurred
            try
            {
                fileData = File.ReadAllText(filename);
            }
            catch
            {
                Console.WriteLine("File was not accessible. Please make sure it exists and you have appropriate permission to read it.");
                return;
            }

            // Get the file contents, convert to lowercase and remove all non-alpha and non-space characters,
            // then get a raw array (still contains duplicates) of all the words
            string[] rawWordArray = WordCountExampleProgram.GetWordsArray(fileData.ToLower());

            // For each for in the array...
            for (int i = 0; i < rawWordArray.Length; i++)
            {
                if (!table.ContainsKey(rawWordArray[i]))
                {
                    // If the table does not already contain the key, add it to the list with a count of 1
                    table.Add(rawWordArray[i], 1);
                }
                else
                {
                    // Otherwise it was already in the table, increment its previous count by one
                    table[rawWordArray[i]] = Convert.ToInt32(table[rawWordArray[i]]) + 1;
                }
            }

            // Make a variable to count total words
            int totalWords = 0;

            // Print out the key and value of each along with some headers
            Console.WriteLine("\nWord" + string.Empty.PadRight(50 - "Word".Length, ' ') + "Count\n" + string.Empty.PadRight(50 + "Count".Length, '-'));
            for (int i = 0; i < table.Count; i++)
            {
                int value = Convert.ToInt32(table.GetByIndex(i));
                totalWords += value;
                Console.WriteLine(String.Format("{0,-50}{1}", table.GetKey(i), value));
            }

            Console.WriteLine("{0,-50}{1}\n", "TOTAL", totalWords);
        }
开发者ID:jakepetroules,项目名称:epgy-archive,代码行数:61,代码来源:WordCountExampleProgram.cs

示例5: PrintKeysAndValues

 public static void PrintKeysAndValues(SortedList myList)
 {
     Console.WriteLine("\t-KEY-\t-VALUE-");
     for (int i = 0; i < myList.Count; i++)
     {
         Console.WriteLine("\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i));
     }
     Console.WriteLine();
 }
开发者ID:oblivious,项目名称:Oblivious,代码行数:9,代码来源:Program.cs

示例6: SortedList

        public void SortedList()
        {
            var list = new SortedList();
            list.Add(5, "Matteo");
            list.Add(4, DateTime.UtcNow);
            list.Add(1, "Pierangeli");

            var firstPosition = list.GetKey(0);
            Assert.That(list[firstPosition], Is.EqualTo("Pierangeli"));
        }
开发者ID:pierangelim,项目名称:advanced-c-sharp,代码行数:10,代码来源:NonGenericCollections.cs

示例7: createViewDatatable

		private void createViewDatatable(SortedList columnOrder)
		{
			ViewDatatable = new DataTable();

			for(int i=0;i<columnOrder.Count; i++)
			{
				viewTableColumnNames viewColumnName;
				Common.Interface.ImportFileColumns dataColumnName;
				string temp = (string)columnOrder.GetKey(
					columnOrder.IndexOfValue(i));
				dataColumnName = convertImportFileColumnsName(temp);
				switch(dataColumnName)
				{
					case Common.Interface.ImportFileColumns.ClubId:
						viewColumnName = viewTableColumnNames.Klubb;
						break;
					case Common.Interface.ImportFileColumns.Email:
						viewColumnName = viewTableColumnNames.Epost;
						break;
					case Common.Interface.ImportFileColumns.Givenname:
						viewColumnName = viewTableColumnNames.Fornamn;
						break;
					case Common.Interface.ImportFileColumns.Lane:
						viewColumnName = viewTableColumnNames.Bana;
						break;
					case Common.Interface.ImportFileColumns.Patrol:
						viewColumnName = viewTableColumnNames.Patrull;
						break;
					case Common.Interface.ImportFileColumns.ShooterClass:
						viewColumnName = viewTableColumnNames.Klass;
						break;
					case Common.Interface.ImportFileColumns.ShooterId:
						viewColumnName = viewTableColumnNames.Skyttekort;
						break;
					case Common.Interface.ImportFileColumns.Surname:
						viewColumnName = viewTableColumnNames.Efternamn;
						break;
					case Common.Interface.ImportFileColumns.WeaponId:
						viewColumnName = viewTableColumnNames.Vapen;
						break;
					default:
						throw new ApplicationException("Unknown datacolumn");
				}
				try
				{
					ViewDatatable.Columns.Add(viewColumnName.ToString(), typeof(string));
				}
				catch(Exception)
				{
				}
			}
		}
开发者ID:WinShooter,项目名称:WinShooter-Legacy,代码行数:52,代码来源:CFileImport.cs

示例8: fun3

        public void fun3()
        {
            SortedList s1 = new SortedList();
            s1.Add(9, 'a');
            s1.Add(5, 'f');
            s1.Add(7, 'h');

            Console.WriteLine(s1.GetKey(0));
            Console.WriteLine(s1.GetByIndex(0));

            foreach (DictionaryEntry de in s1)
            {
                Console.WriteLine("key ={0} value = {1}", de.Key, de.Value);
            }
        }
开发者ID:Aritra23,项目名称:Dot-Net-Practice-Programs,代码行数:15,代码来源:CollectionDemo.cs

示例9: Main

        static void Main(string[] args)
        {
            SortedList mySL = new SortedList();
            mySL.Add("One", "1");
            mySL.Add("Two", "2");
            mySL.Add("Three", "3");

            // Result will be displayed in sorted order as all keys are auto stored in sorted order
            System.Console.WriteLine("KEY\tVALUE");
            System.Console.WriteLine("---\t-----");
            for (int i = 0; i < mySL.Count; i++)
            {
                System.Console.WriteLine("{0}\t{1}", mySL.GetKey(i), mySL.GetByIndex(i));
            }
            System.Console.WriteLine("\nCapacity of this SortedList: {0}", mySL.Capacity);
            System.Console.WriteLine("Does this SortedList contain \"One\" as key: {0}", mySL.Contains("One"));
            System.Console.WriteLine("Number of objects presently in this SortedList: {0}", mySL.Count);
            System.Console.ReadLine();
        }
开发者ID:anuragbhd,项目名称:code,代码行数:19,代码来源:Program.cs

示例10: OrdenarLista

        private void OrdenarLista(ref ListBox listBox)
        {
            SortedList itens = new SortedList();

            foreach (ListItem item in listBox.Items)
            {
                itens.Add(item.Text, item);
            }

            listBox.Items.Clear();

            for (int cont = 0; cont < itens.Count; cont++)
            {
                listBox.Items.Add((ListItem)itens[itens.GetKey(cont)]);
            }
        }
开发者ID:vivermais,项目名称:vivermais,代码行数:16,代码来源:FormRecepcaoPaciente.aspx.cs

示例11: Read


//.........这里部分代码省略.........
				// segment count through SegmentCount property
				// won't have any effect
				if (a.Style == ArrowStyle.Bezier)
					a.InternalSegmentCount = (short)((points.Count - 1) / 3);
				else
					a.InternalSegmentCount = (short)(points.Count - 1);

				// Set the control points
				for(int p = 0; p < points.Count; p++)
					a.ControlPoints[p] = points[p];
				a.UpdateFromPoints();

				// Set brush and pen
				if(brushId != -1)
					a.Brush = (FlowChartX.Brush)brushes[brushId];
				if(pen != null)
					a.Pen = pen;
				if (headPen != null)
					a.HeadPen = headPen;

				objects.Add(idArrow, a);
				zOrder.Add(zIndex, a);
			}

			// Read arrows closing element
			if(count > 0)
				reader.Read();


			// Adjust z-order
			for(i = 0; i < zOrder.Count; i++)
			{
				ChartObject obj = (ChartObject)zOrder.GetByIndex(i);
				obj.ZIndex = (int)zOrder.GetKey(i);
			}


			// Read groups
			ReadMandatory(reader, "Groups",
				"Groups element missing or invalid");
			count = XmlConvert.ToInt32(reader.GetAttribute("Count"));
			for(i = 0; i < count; i++)
			{
				// Read the group element
				ReadMandatory(reader, "Group",
					"Unrecognized group token");

				// Read the main object
				reader.Read();
				id = XmlConvert.ToInt32(reader.GetAttribute("Id"));

				g = _diagram.CreateGroup((ChartObject)objects[id]);

				// Read group's visibility
				reader.Read();
				reader.Read();
				g.Visible = XmlConvert.ToBoolean(reader.Value.ToLower());
				reader.Read();

				// Read AutoDeleteItems flag
				if (_version >= 7)
				{
					reader.Read();
					reader.Read();
					g.AutoDeleteItems = XmlConvert.ToBoolean(reader.Value.ToLower());
					reader.Read();
开发者ID:ChrisMoreton,项目名称:Test3,代码行数:67,代码来源:XmlReader.cs

示例12: ModifyOneRec

        } //InsertOneRec

        /// <summary>
        /// 修改一条记录
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="FieldValueList"></param>
        /// <returns></returns>
        public bool ModifyOneRec(string TableName, SortedList FieldValueList, SortedList PrimaryKeyList)
        {
            System.Data.SqlClient.SqlConnection conn;
            System.Data.SqlClient.SqlDataAdapter dbAdpter;  //数据适配器
            System.Data.SqlClient.SqlCommand dbCommand;  //数据操作命令
            System.Data.SqlClient.SqlCommandBuilder dbCommandBuilder; //提供自动生成表单的命令方法

            string WhereSql;

            WhereSql = this.GetWhereSql(PrimaryKeyList);

            conn = new SqlConnection(mConnectInfo);
            dbCommand = new SqlCommand();
            dbCommand.CommandText = "select * from " + TableName + WhereSql;
            dbCommand.Connection = conn;

            dbAdpter = new SqlDataAdapter(dbCommand);

            dbCommandBuilder = new SqlCommandBuilder(dbAdpter);

            DataTable dt = new DataTable(); ;

            try
            {
                conn.Open(); //建立数据库连接
                dbAdpter.Fill(dt);

                string FieldName;
                object FieldValue;

                //赋新值
                DataRow dr;
                for (int k = 0; k <= dt.Rows.Count - 1; k++)
                {
                    dr = dt.Rows[k];
                    for (int i = 0; i <= FieldValueList.Count - 1; i++)
                    {
                        FieldName = FieldValueList.GetKey(i).ToString();
                        FieldValue = FieldValueList.GetByIndex(i);
                        if (FieldValue == null) FieldValue = Convert.DBNull;
                        dr[FieldName] = FieldValue;
                        System.Diagnostics.Debug.WriteLine(FieldName + "=" + FieldValue);
                    }
                }

                dbAdpter.Update(dt);
                return true;
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                throw new Exception("ModifyOneRec:" + ee.Message);
            }
            finally
            {
                conn.Close();
            }
        }//ModifyOneRec
开发者ID:jquery2005,项目名称:GMIS,代码行数:65,代码来源:CDataOperator.cs

示例13: InsertOneRec

        } //AddOneRec

        /// <summary>
        /// 插入一条记录
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="FieldValueList"></param>
        /// <param name="LocatList"></param>
        /// <param name="BeforeID"></param>
        /// <returns></returns>
        public bool InsertOneRec(string TableName, SortedList FieldValueList, SortedList LocatList, long BeforeID, out bool ModifyOtherID)
        {
            SqlConnection conn; //数据库连接
            SqlDataAdapter dbAdpter;  //数据适配器
            SqlCommand dbCommand;  //数据操作命令
            SqlCommandBuilder dbCommandBuilder; //提供自动生成表单的命令方法
            SqlTransaction MyTransaction = null;  //事务定义

            string WhereSql;
            string LocateStr;
            long CurID = 0;
            string tempIDName;
            tempIDName = TableName.ToUpper() + "ID";

            WhereSql = this.GetWhereSql(LocatList);

            conn = new SqlConnection(mConnectInfo);
            dbCommand = new SqlCommand();
            dbCommand.Connection = conn;

            DataTable dt = new DataTable();
            ModifyOtherID = false;

            try
            {
                conn.Open(); //建立数据库连接

                MyTransaction = conn.BeginTransaction(); //开始事务
                dbCommand.Transaction = MyTransaction;

                //1.设置原来的所有记录为历史记录ZC9993='00'
                LocateStr = "Update " + TableName + " set ZC9993='00' " + WhereSql;
                dbCommand.CommandText = LocateStr;
                dbCommand.ExecuteNonQuery();

                //2.若插入的ID大于当前的ID,则将当前及其后的ID加100
                CurID = Convert.ToInt64(FieldValueList[tempIDName]);
                if (CurID >= BeforeID)
                {
                    LocateStr = "Update " + TableName + " set " + tempIDName + "=" + tempIDName + " + 100 " + WhereSql + " and " + tempIDName + ">=" + BeforeID;
                    dbCommand.CommandText = LocateStr;
                    dbCommand.ExecuteNonQuery();

                    ModifyOtherID = true; //修改其他ID标志位
                }

                //3.添加的记录的标志位ZC9993='10'
                LocateStr = "select * from " + TableName + WhereSql;
                dbCommand.CommandText = LocateStr;
                dbAdpter = new SqlDataAdapter(dbCommand);
                dbCommandBuilder = new SqlCommandBuilder(dbAdpter);

                dbAdpter.Fill(dt);

                string FieldName;
                object FieldValue;

                //赋新值
                DataRow dr = dt.NewRow();

                for (int i = 0; i <= FieldValueList.Count - 1; i++)
                {
                    FieldName = FieldValueList.GetKey(i).ToString();
                    FieldValue = FieldValueList.GetByIndex(i);
                    dr[FieldName] = FieldValue;
                }

                //新记录的标志位为10
                if (FieldValueList.ContainsKey("ZC9993"))
                {
                    dr["ZC9993"] = "10";
                }

                //添加一条记录
                dt.Rows.Add(dr);

                dbAdpter.Update(dt);

                //提交事务
                MyTransaction.Commit();

                return true;
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                MyTransaction.Rollback(); //事务回滚 
                ModifyOtherID = false;
                throw new Exception("InsertRecInMainSet:" + ee.Message);
            }
            finally
//.........这里部分代码省略.........
开发者ID:jquery2005,项目名称:GMIS,代码行数:101,代码来源:CDataOperator.cs

示例14: TestGetKeyBasic

        public void TestGetKeyBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);

            SortedList sl2 = null;

            StringBuilder sbl3 = new StringBuilder(99);
            StringBuilder sbl4 = new StringBuilder(99);
            StringBuilder sblWork1 = new StringBuilder(99);

            string s1 = null;
            string s2 = null;

            int i = 0;
            //
            // 	Constructor: Create SortedList using this as IComparer and default settings.
            //
            sl2 = new SortedList(this);

            //  Verify that the SortedList is not null.
            Assert.NotNull(sl2);

            //  Verify that the SortedList is empty.
            Assert.Equal(0, sl2.Count);

            //    Testcase: GetKey - key at index 0 , ArgExc expected
            Assert.Throws<ArgumentOutOfRangeException>(() =>
                {
                    sl2.GetKey(0);
                });

            //   Testcase: GetKey - null val, should pass
            sl2["first key"] = (string)null;
            Assert.Equal(1, sl2.Count);

            //   Testcase: vanila Set
            sl2.Clear();
            //   Testcase: add key-val pairs
            for (i = 0; i < 50; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                sl2.Add(s1, s2);
            }

            //
            //   now get their keys using GetKey
            //
            for (i = 0; i < 50; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();
                Assert.True(((string)sl2.GetKey(sl2.IndexOfKey(s1))).Equals(s1));
            }

            Assert.Equal(50, sl2.Count);
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:67,代码来源:GetKeyTests.cs

示例15: IsConnectionOptimal

    /**
     * Checks if connection to the current address is optimal. 
     * Scores can vary over time, and there might be "tight" race for the optimal.
     * We may end up in a situation that we are trimming a connection that is not optimal, even 
     * though the penalty for not using the optimal is marginal. The following algorithm
     * checks that the current selection is in the top-percentile and also the penalty for not
     * using the current optimal is marginal. 
     * @param curr_address address of the current connection target. 
     * @param score_table candidate addresses sorted by scores.
     * @param max_rank maximum rank within the score table, beyond which connection 
     *                 is treated suboptimal.
     */
    protected bool IsConnectionOptimal(Address curr_address, SortedList score_table, int max_rank) {
      if (score_table.Count == 0) {
        if (LogEnabled) {
          ProtocolLog.Write(ProtocolLog.SCO, 
                            String.Format("SCO local: {0}, Not sufficient scores available to determine optimality: {1}.", 
                                          _node.Address, curr_address));
        }
        return true;
      }
            
      bool optimal = false; //if shortcut is optimal.
      bool doubtful = false; //if there is doubt on optimality of this connection.
      int curr_rank = score_table.IndexOfValue(curr_address);
      if (curr_rank == -1) {
        if (LogEnabled) {
          ProtocolLog.Write(ProtocolLog.SCO, 
                            String.Format("SCO local: {0}, No score available for current: {1}.", 
                                          _node.Address, curr_address));
        }
        
        //doubtful case
        doubtful = true;
      } else if (curr_rank == 0) {
        //definitely optimal
        optimal = true;
      } else if (curr_rank <= max_rank) {
        //not the minimum, but still in top percentile.
        double penalty = (double) score_table.GetKey(curr_rank)/(double) score_table.GetKey(0);
        if (LogEnabled) {
          ProtocolLog.Write(ProtocolLog.SCO, 
                            String.Format("SCO local: {0}, Penalty for using current: {1} penalty: {2}).", 
                                          _node.Address, curr_address, penalty));
        }

        //we allow for 10 percent penalty for not using the optimal
        if (penalty < 1.1 ) {
          optimal = true;
        }
      } else {
        if (LogEnabled) {        
          ProtocolLog.Write(ProtocolLog.SCO, 
                            String.Format("SCO local: {0}, Current: {1} too poorly ranked: {2}.", 
                                  _node.Address, curr_address, curr_rank));
        }
      }

      /** 
       * If we are doubtful about the current selection, we will continue to treat it
       * optimal for sometime.
       */
      string log = null;
      lock(_sync) {
        if (optimal) {
          //clear the entry
          _doubts_table.Remove(curr_address);
        } 
        else if (doubtful) { //if we have doubt about the selection
          //make sure that we are not being to generous
          if (!_doubts_table.ContainsKey(curr_address)) {
            _doubts_table[curr_address] = 1;
          } 
          int idx = (int) _doubts_table[curr_address];
          if (idx < MAX_DOUBT_BENEFITS) {
            _doubts_table[curr_address] = idx + 1;
            log = String.Format("SCO local: {0}, Giving benfit: {1} of doubt for current: {2}.", 
                                       _node.Address, idx, curr_address);
            optimal = true;
          } else {
            log = String.Format("SCO local: {0}, Reached quota: {1} on doubts for current: {2}.", 
                                _node.Address, idx, curr_address);
          }
        }
        
        //all efforts to make the connection look optimal have failed
        if (!optimal) {
          //clear the entry
          _doubts_table.Remove(curr_address);          
        }
      } //end of lock
      if (LogEnabled) {
        ProtocolLog.Write(ProtocolLog.SCO, log);
      }
      return optimal;
    }
开发者ID:twchoi,项目名称:tmp-brunet-deetoo,代码行数:96,代码来源:StructuredShortcutConnectionOverlord.cs


注:本文中的System.Collections.SortedList.GetKey方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。