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


C# Dictionary.TryGetValue方法代码示例

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


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

示例1: RestoreListViewSelected

        public void RestoreListViewSelected()
        {
            try
            {
                if (listBox != null && oldItem != null && oldItems != null)
                {
                    if (this.allSelected == true)
                    {
                        listBox.SelectAll();
                        return;
                    }

                    //このUnselectAll()は無いと正しく復元出来ない状況があり得る
                    listBox.UnselectAll();

                    //上限越えの場合は、選択を解除して終了。
                    if (oldItems.Count >= this.MaxRestoreNum) return;

                    //選択数が少ないときは逆に遅くなる気もするが、Dictionaryにしておく
                    var listKeys = new Dictionary<ulong, object>();

                    if (getKey == null)
                    {
                        getKey = CtrlCmdDefEx.GetKeyFunc(oldItem.GetType());
                    }

                    foreach (object listItem1 in listBox.Items)
                    {
                        //重複するキーは基本的に無いという前提
                        try
                        {
                            listKeys.Add(getKey(listItem1), listItem1);
                        }
                        catch { }
                    }

                    object setItem;
                    if (listKeys.TryGetValue(getKey(oldItem), out setItem))
                    {
                        listBox.SelectedItem = setItem;
                    }

                    foreach (object oldItem1 in oldItems)
                    {
                        if (listKeys.TryGetValue(getKey(oldItem1), out setItem))
                        {
                            //数が多いとき、このAddが致命的に遅い
                            listBox.SelectedItems.Add(setItem);
                        }
                    }

                    //画面更新が入るので最後に実行する。SelectedItem==nullのときScrollIntoViewは何もしない。
                    listBox.ScrollIntoView(listBox.SelectedItem);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
开发者ID:xceza7,项目名称:EDCB,代码行数:60,代码来源:ListViewSelectedKeeper.cs

示例2: BatArg

        public BatArg(Dictionary<string, string> keys)
        {
            Model = (BatModel)(int.Parse(keys["Model"]));
            Hierarchy = (DestHierarchy)(int.Parse(keys["DestHierarchy"]));
            PC = keys.ContainsKey("PC");
            IOS = keys.ContainsKey("IOS");
            AND = keys.ContainsKey("AND");
            if (keys.TryGetValue("SrcFolder", out SrcFolder))	
			{
				SrcFolder = Application.dataPath + SrcFolder;
				SrcFolder.Replace("\\", "/");
			}
            if (keys.TryGetValue("SrcFolderName", out SrcFolderName)) SrcFolderName.Replace("\\", "/");
            SearchLoop = keys.ContainsKey("SearchLoop");
            if (keys.TryGetValue("SearchPrefix", out SearchPrefix))	SearchPrefix.Replace("\\", "/");
            if (keys.TryGetValue("DestFolder", out DestFolderPath))	
			{
				DestFolderPath = Application.dataPath + "/../.." + DestFolderPath;
				DestFolderPath.Replace("\\", "/");
			}
            if (keys.TryGetValue("DestFolderName", out DestFolderName))	DestFolderName.Replace("\\", "/");
			
//			Debug.Log(JsonWriter.Serialize(this));

        }
开发者ID:seenen,项目名称:HerosTechBak_Seenen,代码行数:25,代码来源:BatArg.cs

示例3: EmailPassword

        /// <summary>
        /// Emails the given password to the given emailaddress. No username is specified.
        /// </summary>
        /// <param name="password">The password to email</param>
        /// <param name="emailAddress">The recipient's emailaddress.</param>
        /// <param name="emailTemplate">The email template.</param>
        /// <param name="emailData">The email data.</param>
        /// <returns>true if succeeded, false otherwise</returns>
        public static bool EmailPassword(string password, string emailAddress, string emailTemplate, Dictionary<string, string> emailData)
        {
            StringBuilder mailBody = new StringBuilder(emailTemplate);

            string applicationURL = string.Empty;
            emailData.TryGetValue("applicationURL", out applicationURL);

            if (!string.IsNullOrEmpty(emailTemplate))
            {
                // Use the existing template to format the body
                string siteName = string.Empty;
                emailData.TryGetValue("siteName", out siteName);

                mailBody.Replace("[URL]", applicationURL);
                mailBody.Replace("[SiteName]", siteName);
                mailBody.Replace("[Password]", password);
            }

            // format the subject
            string subject = string.Empty;
            emailData.TryGetValue("emailPasswordSubject", out subject);
            subject += applicationURL;

            string fromAddress = string.Empty;
            emailData.TryGetValue("defaultFromEmailAddress", out fromAddress);

            // send it
            // host and smtp credentials are set in .config file
            SmtpClient client = new SmtpClient();
            client.Send(fromAddress, emailAddress, subject, mailBody.ToString());
            return true;
        }
开发者ID:priaonehaha,项目名称:HnD,代码行数:40,代码来源:HnDGeneralUtils.cs

示例4: GetClosest

    /// <summary>Returns at most the 4 closest addresses in order.</summary>
    protected List<Connection> GetClosest(List<Connection> cons)
    {
      List<Connection> closest = new List<Connection>(cons);

      // Since MeasuredLatency could change the duration of our sorting we make
      // a copy as necessary
      Dictionary<Connection, double> latencies = new Dictionary<Connection, double>();

      Comparison<Connection> comparer = delegate(Connection x, Connection y) {
        double lat_x, lat_y;
        if(!latencies.TryGetValue(x, out lat_x)) {
          lat_x = _ncservice.GetMeasuredLatency(x.Address);
          latencies[x] = lat_x;
        }
        if(!latencies.TryGetValue(y, out lat_y)) {
          lat_y = _ncservice.GetMeasuredLatency(y.Address);
          latencies[y] = lat_y;
        }

        // Remember that smaller is better but -1 is bad...
        // If either is smaller than 0 invert the comparison..
        if(lat_x < 0 || lat_y < 0) {
          return lat_y.CompareTo(lat_x);
        } else {
          return lat_x.CompareTo(lat_y);
        }
      };

      closest.Sort(comparer);
      if(closest.Count > 4) {
        closest.RemoveRange(4, closest.Count - 4);
      }
      return closest;
    }
开发者ID:johnynek,项目名称:brunet,代码行数:35,代码来源:NCTunnelOverlap.cs

示例5: Popup

        public Popup(Dictionary<string, object> options)
        {
            object name;
            if (options.TryGetValue("name", out name)) {
                _name = (string)name;
            }

            object depth;
            if (options.TryGetValue("depth", out depth)) {
                _depth = (int)depth;
            }
        }
开发者ID:deltaDNA,项目名称:unity-sdk,代码行数:12,代码来源:Popup.cs

示例6: ReadClassDataContractMembers

        private static void ReadClassDataContractMembers(DataContractJsonSerializer serializer, ClassDataContract dataContract, Dictionary<string, object> deserialzedValue, object newInstance, XmlObjectSerializerReadContextComplexJson context)
        {
            if (dataContract.BaseContract != null)
            {
                ReadClassDataContractMembers(serializer, dataContract.BaseContract, deserialzedValue, newInstance, context);
            }
            for (int i = 0; i < dataContract.Members.Count; i++)
            {
                DataMember member = dataContract.Members[i];
                object currentMemberValue;
                if (deserialzedValue.TryGetValue(XmlConvert.DecodeName(dataContract.Members[i].Name), out currentMemberValue) ||
                    dataContract.IsKeyValuePairAdapter && deserialzedValue.TryGetValue(XmlConvert.DecodeName(dataContract.Members[i].Name.ToLowerInvariant()), out currentMemberValue))
                {
                    if (member.MemberType.GetTypeInfo().IsPrimitive || currentMemberValue == null)
                    {
                        SetMemberValue(newInstance, serializer.ConvertObjectToDataContract(member.MemberTypeContract, currentMemberValue, context), dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
                    }
                    else
                    {
                        context.PushKnownTypes(dataContract);
                        object subMemberValue = serializer.ConvertObjectToDataContract(member.MemberTypeContract, currentMemberValue, context);
                        Type declaredType = (member.MemberType.GetTypeInfo().IsGenericType && member.MemberType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
                            ? Nullable.GetUnderlyingType(member.MemberType)
                            : member.MemberType;

                        if (!(declaredType == Globals.TypeOfObject && subMemberValue.GetType() == Globals.TypeOfObjectArray) && declaredType != subMemberValue.GetType())
                        {
                            DataContract memberValueContract = DataContract.GetDataContract(subMemberValue.GetType());
                            context.CheckIfTypeNeedsVerifcation(member.MemberTypeContract, memberValueContract);
                        }

                        if (member.IsGetOnlyCollection)
                        {
                            PopulateReadOnlyCollection(newInstance, member, (IEnumerable)subMemberValue);
                        }
                        else
                        {
                            SetMemberValue(newInstance, subMemberValue, dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
                        }
                        context.PopKnownTypes(dataContract);
                    }
                }
                else if (member.IsRequired)
                {
                    XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(dataContract.MemberNames[i].Value, dataContract.UnderlyingType);
                }
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:48,代码来源:ObjectToDataContractConverterHelper.cs

示例7: BuildSummary

        public static TypeSummary[] BuildSummary(MigrationReport report)
        {
            IDictionary<string, TypeSummary> types = new Dictionary<string, TypeSummary>();

            foreach (MigrationReportMessage message in report.Messages)
            {
                TypeSummary type;
                string sourceType = message.SourceType ?? string.Empty;

                if (!types.TryGetValue(sourceType, out type))
                {
                    type = new TypeSummary(sourceType);
                    types.Add(sourceType, type);
                }

                type.AddMessage(message);
            }

            int typeCount = types.Count;
            string[] keys = new string[typeCount];
            TypeSummary[] values = new TypeSummary[typeCount];
            types.Keys.CopyTo(keys, 0);
            types.Values.CopyTo(values, 0);
            Array.Sort(keys, values);
            return values;
        }
开发者ID:Saleslogix,项目名称:SLXMigration,代码行数:26,代码来源:MigrationReportEditor.cs

示例8: InstantiatePrefabs

        private void InstantiatePrefabs(Vector3[,] worldPositions, string[,] map, Dictionary<string, GameObject> objectDictionary)
        {
            int width = map.GetLength(0);
            int height = map.GetLength(1);

            GameObject container = new GameObject("Generated Map Container");
            container.transform.parent = this.transform;
            Dictionary<string, GameObject> containerDictionary = new Dictionary<string, GameObject>(objectDictionary.Keys.Count);
            foreach (string typeName in objectDictionary.Keys) {
            GameObject typeContainer = new GameObject(typeName);
            typeContainer.transform.parent = container.transform;
            containerDictionary.Add(typeName, typeContainer);
            }

            container.transform.parent = this.transform;
            for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                string mapValue = map[i, j];

                GameObject prefab;
                if (mapValue != null && objectDictionary.TryGetValue(mapValue, out prefab)) {
                    GameObject instance = (GameObject)Instantiate(prefab);
                    instance.transform.position = worldPositions[i, j];
                    instance.transform.parent = containerDictionary[mapValue].transform;

                    if (instance.CompareTag("Player")) {
                        player = instance;
                    }
                }
            }
            }
        }
开发者ID:jschiff,项目名称:SphericalHorse,代码行数:32,代码来源:GridBuilder.cs

示例9: loginButton_Click

        // TODO: Insert code to perform custom authentication using the provided username and password
        // (See http://go.microsoft.com/fwlink/?LinkId=35339).
        // The custom principal can then be attached to the current thread's principal as follows:
        //     My.User.CurrentPrincipal = CustomPrincipal
        // where CustomPrincipal is the IPrincipal implementation used to perform authentication.
        // Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
        // such as the username, display name, etc.
        private void loginButton_Click(System.Object sender, System.EventArgs e)
        {
            FixtureBuilder fb = new FixtureBuilder();

            Dictionary<string, int> userDictionary = new Dictionary<string, int>();
            userDictionary = fb.getUsersAndIds();

            string username = usernameTextBox.Text.ToLower();
            userId = -1;

            if (string.IsNullOrEmpty(username)) {
                Interaction.MsgBox("Please enter your username");

            } else {
                if (userDictionary.ContainsKey(username)) {
                    userDictionary.TryGetValue(username, out userId);
                    My.MyProject.Forms.FixturesForm.currentUser = userId;
                    My.MyProject.Forms.MenuForm.Show();
                    this.Close();
                } else {
                    Interaction.MsgBox("Username not recognised");
                    usernameTextBox.Clear();
                }

            }
        }
开发者ID:hamptons,项目名称:PlaceYourBets,代码行数:33,代码来源:LoginForm.cs

示例10: GenerateComplexObject

        private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
        {
            object result = null;

            if (createdObjectReferences.TryGetValue(type, out result))
            {
                return result;
            }

            if (type.IsValueType)
            {
                result = Activator.CreateInstance(type);
            }
            else
            {
                ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
                if (defaultCtor == null)
                {
                    return null;
                }

                result = defaultCtor.Invoke(new object[0]);
            }
            createdObjectReferences.Add(type, result);
            SetPublicProperties(type, result, createdObjectReferences);
            SetPublicFields(type, result, createdObjectReferences);
            return result;
        }
开发者ID:vrsrajkumarbapu,项目名称:Contact-Manager-Demo,代码行数:28,代码来源:ObjectGenerator.cs

示例11: GetCentroid

        public static TermVector GetCentroid(IEnumerable<TermVector> vectors)
        {
            Dictionary<string, long> sum = new Dictionary<string, long>();

            int vectorCount = 0;
            // Sum the lengths of dimensions
            foreach (TermVector vector in vectors)
            {
                vectorCount++;
                foreach (string term in vector.Terms)
                {
                    long count = 0;
                    sum.TryGetValue(term, out count);
                    sum.Remove(term);
                    sum.Add(term, count + vector.GetDimensionLength(term));
                }
            }

            // Divide the dimensions
            Dictionary<string, int> centroid = new Dictionary<string, int>();
            foreach (KeyValuePair<string, long> dimension in sum)
            {
                centroid.Add(dimension.Key, (int)(dimension.Value / vectorCount));
            }

            return new TermVector(centroid);
        }
开发者ID:tristanstcyr,项目名称:SPIMI,代码行数:27,代码来源:TermVector.cs

示例12: AddMaterialReference

        /// <summary>
        /// Function to add a new material reference and returning its index in the material reference array.
        /// </summary>
        /// <param name="material"></param>
        /// <param name="fontAsset"></param>
        /// <param name="materialReferences"></param>
        /// <param name="materialReferenceIndexLookup"></param>
        /// <returns></returns>
        public static int AddMaterialReference(Material material, TMP_FontAsset fontAsset, MaterialReference[] materialReferences, Dictionary<int, int> materialReferenceIndexLookup)
        {
            int materialID = material.GetInstanceID();
            int index = 0;

            if (materialReferenceIndexLookup.TryGetValue(materialID, out index))
            {
                return index;
            }
            else
            {
                index = materialReferenceIndexLookup.Count;

                // Add new reference index
                materialReferenceIndexLookup[materialID] = index;

                materialReferences[index].index = index;
                materialReferences[index].fontAsset = fontAsset;
                materialReferences[index].spriteAsset = null;
                materialReferences[index].material = material;
                materialReferences[index].isDefaultMaterial = materialID == fontAsset.material.GetInstanceID() ? true : false;
                //materialReferences[index].padding = 0;
                materialReferences[index].referenceCount = 0;

                return index;
            }
        }
开发者ID:Reticulatas,项目名称:Embargo,代码行数:35,代码来源:MaterialReferenceManager.cs

示例13: PrepareRegional

 public static IEnumerable<RegionalNode> PrepareRegional(IEnumerable<ScheduleInfo> model,out Dictionary<DayOfWeek,String> days)
 {
     var result = new Dictionary<String, RegionalNode>();
     days = new Dictionary<DayOfWeek, string>(7);
     var mappings = new Dictionary<DayOfWeek, String>
                {
                    {DayOfWeek.Monday, GSchedule.Mo},
                    {DayOfWeek.Tuesday, GSchedule.Tu},
                    {DayOfWeek.Wednesday, GSchedule.We},
                    {DayOfWeek.Thursday, GSchedule.Th},
                    {DayOfWeek.Friday, GSchedule.Fr},
                    {DayOfWeek.Saturday, GSchedule.Sa},
                    {DayOfWeek.Sunday, GSchedule.Su},
                };
     foreach (var item in model)
     {
         var time = String.Format("{0:hh\\:mm}-{1:hh\\:mm}", item.Starts, item.Ends);
         RegionalNode node;
         if (!result.TryGetValue(time, out node))
         {
             result[time] = node = new RegionalNode(time);
         }
         node.AddItem(item);
         var dayOfWeek = (DayOfWeek) item.Day;
         if (!days.ContainsKey(dayOfWeek))
         {
             days.Add(dayOfWeek,mappings[dayOfWeek]);
         }
     }
     return result.Values;
 }
开发者ID:linguado,项目名称:mundo-site,代码行数:31,代码来源:CalendarHelper.cs

示例14: Init

 public void Init(IDictionary<DateTime, int> dates, DateTime selectedDate)
 {
   Dictionary<int, TreeNode> dictionary1 = new Dictionary<int, TreeNode>();
   Dictionary<int, TreeNode> dictionary2 = new Dictionary<int, TreeNode>();
   this.treeView.BeginUpdate();
   foreach (KeyValuePair<DateTime, int> keyValuePair in (IEnumerable<KeyValuePair<DateTime, int>>) dates)
   {
     DateTime key = keyValuePair.Key;
     int year = key.Year;
     int month = key.Month;
     int day = key.Day;
     TreeNode node1;
     if (!dictionary1.TryGetValue(year, out node1))
     {
       node1 = (TreeNode) new DateNode(key, "yyyy");
       dictionary1.Add(year, node1);
       this.treeView.Nodes.Add(node1);
     }
     TreeNode node2;
     if (!dictionary2.TryGetValue(month, out node2))
     {
       node2 = (TreeNode) new DateNode(key, "MMM");
       dictionary2.Add(month, node2);
       node1.Nodes.Add(node2);
     }
     DayNode dayNode = new DayNode(key, keyValuePair.Value);
     node2.Nodes.Add((TreeNode) dayNode);
     if (key == selectedDate)
       this.treeView.SelectedNode = (TreeNode) dayNode;
   }
   this.treeView.TreeViewNodeSorter = (IComparer) new DateNodeComparer();
   this.treeView.Sort();
   this.treeView.EndUpdate();
   this.UpdateOKButtonStatus();
 }
开发者ID:smther,项目名称:FreeOQ,代码行数:35,代码来源:DataSeriesCalendarForm.cs

示例15: FindType

        Type FindType(string @namespace, string name)
        {
            if (_types == null)
            {
                _types = new Dictionary<string, Dictionary<string, Type>>();
                foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                    foreach (Type type in a.GetTypes())
                    {
                        var attribute = type.GetCustomAttribute<MarkupElementAttribute>(false);
                        if (attribute != null)
                        {
                            Dictionary<string, Type> typesInNamespace;
                            if (!_types.TryGetValue(attribute.NameSpace, out typesInNamespace))
                            {
                                typesInNamespace = new Dictionary<string, Type>();
                                _types.Add(attribute.NameSpace, typesInNamespace);
                            }
                            typesInNamespace.Add(attribute.Name, type);
                        }
                    }
            }

            try
            {
                return _types[@namespace][name];
            }
            catch (KeyNotFoundException e)
            {
                throw new Exception(String.Format("Type '{0}.{1}' is not found.", @namespace, name), e);
            }
        }
开发者ID:Fedorm,项目名称:core-master,代码行数:31,代码来源:ObjectFactory.cs


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