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


C# Dictionary.ContainsKey方法代码示例

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


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

示例1: IsPermutationByCharacterCount

        public static bool IsPermutationByCharacterCount(string s, string t)
        {
            if (s.Length != t.Length) return false;

            var counts = new Dictionary<char, int>();

            foreach (var c in s)
            {
                if (!counts.ContainsKey(c)) counts[c] = 0;

                counts[c]++;
            }

            foreach (var c in t)
            {
                if (!counts.ContainsKey(c)) counts[c] = 0;

                if (--counts[c] < 0)
                {
                    return false;
                }
            }

            return true;
        }
开发者ID:longda,项目名称:speedball,代码行数:25,代码来源:Permutation.cs

示例2: Intersect

        public int[] Intersect(int[] nums1, int[] nums2)
        {
            //Solution can be:(this one is slower than below)
            //var map1 = nums1.GroupBy(n => n).ToDictionary(g => g.Key, g => g.Count());
            //return nums2.Where(n => map1.ContainsKey(n) && map1[n]-- > 0).ToArray();
            //Or:

            Dictionary<int, int> numbCount=new Dictionary<int, int>();
            foreach (int i in nums1)
            {
                if (!numbCount.ContainsKey(i))
                {
                    numbCount.Add(i,0);
                }
                numbCount[i]++;
            }

            List<int> ls = new List<int>();
            foreach (int j in nums2)
            {
                if (numbCount.ContainsKey(j) && numbCount[j] > 0)
                {
                    ls.Add(j);
                    numbCount[j]--;
                }
            }

            return ls.ToArray();
        }
开发者ID:husthk986,项目名称:BlackSwan,代码行数:29,代码来源:ArrayIntersection.cs

示例3: AddPortal

        private static void AddPortal(XmlNode portal)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            XmlNodeList childList = portal.ChildNodes;
            for (int i = 0; i < childList.Count; i++)
                data.Add(childList.Item(i).Name, childList.Item(i).InnerText);

            if (!data.ContainsKey("toid")) return;
            try
            {
                Dictionary<byte,PortalInfo> tmpdic;
                System.Globalization.CultureInfo culture;
                culture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
                PortalInfo nPortal = new PortalInfo(int.Parse(data["toid"]), float.Parse(data["x"],culture), float.Parse(data["y"],culture), float.Parse(data["z"],culture));
                if (data.ContainsKey("mapid"))
                    nPortal.m_mapID = byte.Parse(data["mapid"]);
                if (!portals.ContainsKey(byte.Parse(data["toid"])))
                {
                    tmpdic = new Dictionary<byte, PortalInfo>();
                    tmpdic.Add(byte.Parse(data["fromid"]), nPortal);
                    portals.Add(byte.Parse(data["toid"]), tmpdic);
                }
                else
                {
                    tmpdic = portals[byte.Parse(data["toid"])];
                    tmpdic.Add(byte.Parse(data["fromid"]), nPortal);
                }

            }
            catch (Exception e) { Logger.ShowError("cannot parse: " + data["toid"],null); Logger.ShowError(e,null); return; }
        }
开发者ID:Willyham,项目名称:SagaRO2,代码行数:31,代码来源:PortalManager.cs

示例4: BatchAdd

 protected void BatchAdd(Item item1, Item item2, Item item3, Item item4, Item item5, Section[] sectionList)
 {
     var itemList = new[] {item1, item2, item3, item4, item5};
     var itemDictionary = new Dictionary<ItemCategory, Item>();
     foreach (var item in itemList)
     {
         if (item != null) itemDictionary.Add(item.Category, item);
     }
     var topList = new List<Section>();
     var bottomList = new List<Section>();
     var leftList = new List<Section>();
     var rightList = new List<Section>();
     foreach (var section in sectionList)
     {
         topList.Add(Section.Line(section.GridX, section.GridY + section.Row, section.Column, section.OffsetX,
             section.OffsetY));
         bottomList.Add(Section.Line(section.GridX, section.GridY - 1, section.Column, section.OffsetX,
             section.OffsetY));
         leftList.Add(Section.Tower(section.GridX - 1, section.GridY, section.Row, section.OffsetX,
             section.OffsetY));
         rightList.Add(Section.Line(section.GridX + section.Column, section.GridY, section.Row, section.OffsetX,
             section.OffsetY));
     }
     ObjectData.Add(itemDictionary[ItemCategory.Body].Clone, sectionList);
     if (itemDictionary.ContainsKey(ItemCategory.TopCap))
         ObjectData.Add(itemDictionary[ItemCategory.TopCap].Clone, topList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.BottomCap))
         ObjectData.Add(itemDictionary[ItemCategory.BottomCap].Clone, bottomList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.LeftCap))
         ObjectData.Add(itemDictionary[ItemCategory.LeftCap].Clone, leftList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.RightCap))
         ObjectData.Add(itemDictionary[ItemCategory.RightCap].Clone, rightList.ToArray());
 }
开发者ID:simonrouse9461,项目名称:CSE_3902_Mario,代码行数:33,代码来源:LevelKernel.cs

示例5: CheckAccept

	public override bool CheckAccept()
	{
		Dictionary<int, int> dicHaveItem = new Dictionary<int, int>();
		InvenSlot[] invens = ItemMgr.HadItemManagement.Inven.invenSlots;
		foreach( InvenSlot inven in invens)
		{
			if( inven != null && inven.realItem != null)
			{
				int itemID = inven.realItem.item.ItemID;

				if( dicHaveItem.ContainsKey( itemID))
					dicHaveItem[itemID] += 1;
				else
					dicHaveItem.Add( itemID, 1);
			}
		}

		// 아이템 소유 & 수량 체크
		if( !dicHaveItem.ContainsKey( ItemID))
			return false;

		int count = dicHaveItem[ItemID];
		if( ItemCount > count)
			return false;

		return true;
	}
开发者ID:ftcaicai,项目名称:ArkClient,代码行数:27,代码来源:QuestClasses.cs

示例6: GetEntityDataFromType

        protected virtual Dictionary<string, KeyValuePair<string, string>> GetEntityDataFromType(Type type)
        {
            Dictionary<string, KeyValuePair<string, string>> res = new Dictionary<string, KeyValuePair<string, string>>();
            foreach (Attribute attr in type.GetCustomAttributes())
            {
                if (attr is SemanticEntityAttribute)
                {
                    SemanticEntityAttribute semantics = (SemanticEntityAttribute)attr;
                    // we can only support mapping to a single semantic entity, the derived type is set first, so that is what we use
                    if (!res.ContainsKey(semantics.Prefix))
                    {
                        res.Add(semantics.Prefix, new KeyValuePair<string, string>(semantics.Vocab, semantics.EntityName));
                    }
                }
                if (attr is SemanticDefaultsAttribute)
                {
                    SemanticDefaultsAttribute semantics = (SemanticDefaultsAttribute)attr;
                    res.Add(semantics.Prefix, new KeyValuePair<string, string>(semantics.Vocab, String.Empty));
                }
            }

            //Add default mapping if none was specified on entity
            if (!res.ContainsKey(string.Empty))
            {
                res.Add(string.Empty, new KeyValuePair<string, string>(ViewModel.CoreVocabulary, string.Empty));
            }

            return res;
        }
开发者ID:sdl,项目名称:dxa-web-application-dotnet,代码行数:29,代码来源:BaseModelBuilder.cs

示例7: Fill

        public Dictionary<string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                               OSHttpResponse httpResponse, Dictionary<string, object> requestParameters,
                                               ITranslator translator, out string response)
        {
            response = null;
            var vars = new Dictionary<string, object>();

            if (requestParameters.ContainsKey("ResetMenu"))
            {
                PagesMigrator.ResetToDefaults();
                response = "Menu: "+ translator.GetTranslatedString("ChangesSavedSuccessfully");
                return null;
            }
            if (requestParameters.ContainsKey("ResetSettings"))
            {
                SettingsMigrator.ResetToDefaults(webInterface);
                response = "WebUI: "+ translator.GetTranslatedString("ChangesSavedSuccessfully");
                return null;
            }

            vars.Add("FactoryReset", translator.GetTranslatedString("FactoryReset"));
            vars.Add("ResetMenuText", translator.GetTranslatedString("ResetMenuText"));
            vars.Add("ResetSettingsText", translator.GetTranslatedString("ResetSettingsText"));
            vars.Add("ResetMenuInfoText", translator.GetTranslatedString("ResetMenuText"));
            vars.Add("ResetSettingsInfoText", translator.GetTranslatedString("ResetSettingsInfoText"));
            vars.Add("Reset", translator.GetTranslatedString("Reset"));

            return vars;
        }
开发者ID:Virtual-Universe,项目名称:Virtual-Universe,代码行数:29,代码来源:factory_reset.cs

示例8: RulerGivenSkillContainerSkill

 public RulerGivenSkillContainerSkill(IRulerGivenSkill InnerSkill, Allegiance al)
 {
     innerSkillType = InnerSkill.GetType();
     Allegiance = al;
     masterList = new Dictionary<Player, IRulerGivenSkill>();
     var trigger = new AutoNotifyPassiveSkillTrigger(
         this,
         DistributeSkills,
         TriggerCondition.OwnerIsSource
     ) { IsAutoNotify = false, AskForConfirmation = false };
     var trigger2 = new AutoNotifyPassiveSkillTrigger(
         this,
         (p, e, a) =>
         {
             if (a.Source.Allegiance == Allegiance && !masterList.ContainsKey(a.Source))
             {
                 DistributeSkills(Owner, null, null);
             }
             if (a.Source.Allegiance != Allegiance && masterList.ContainsKey(a.Source))
             {
                 ISkill skill = masterList[a.Source];
                 masterList.Remove(a.Source);
                 Game.CurrentGame.PlayerLoseAdditionalSkill(a.Source, skill, true);
             }
         },
         TriggerCondition.Global
     ) { IsAutoNotify = false, AskForConfirmation = false };
     Triggers.Add(GameEvent.PlayerGameStartAction, trigger);
     Triggers.Add(GameEvent.PlayerChangedAllegiance, trigger2);
     IsAutoInvoked = null;
     IsRulerOnly = true;
 }
开发者ID:kingling,项目名称:sgs,代码行数:32,代码来源:RulerGivenSkillContainerSkill.cs

示例9: Create

 public IMMDModelPart Create(int triangleCount, MMDVertexNm[] Vertices, Dictionary<string, object> OpaqueData)
 {
     IndexBuffer indexBuffer = null;
     if (OpaqueData.ContainsKey("IndexBuffer"))
         indexBuffer = OpaqueData["IndexBuffer"] as IndexBuffer;
     Vector2[] extVert = null;
     if (OpaqueData.ContainsKey("VerticesExtention"))
         extVert = OpaqueData["VerticesExtention"] as Vector2[];
     if (indexBuffer == null)
         throw new ArgumentException("MMDModelPartXBoxFactoryのOpaqueDataには\"IndexBuffer\"キーとIndexBufferオブジェクトが必要です。", "OpaqueData");
     if (extVert == null)
         throw new ArgumentException("MMDModelPartXboxFactoryのOpaqueDataには\"VerticesExtention\"キーが必要です。", "OpaqueData");
     if (Vertices is MMDVertexNmTx[])
     {
         if (Vertices is MMDVertexNmTxVc[])
             return new MMDXBoxModelPartPNmTxVc(triangleCount, (MMDVertexNmTxVc[])Vertices, extVert, indexBuffer);
         else
             return new MMDXBoxModelPartPNmTx(triangleCount, (MMDVertexNmTx[])Vertices, extVert, indexBuffer);
     }
     else
     {
         if (Vertices is MMDVertexNmVc[])
             return new MMDXBoxModelPartPNmVc(triangleCount, (MMDVertexNmVc[])Vertices, extVert, indexBuffer);
         else
             return new MMDXBoxModelPartPNm(triangleCount, (MMDVertexNm[])Vertices, extVert, indexBuffer);
     }
 }
开发者ID:himapo,项目名称:ccm,代码行数:27,代码来源:MMDXBoxModelPartFactory.cs

示例10: Main

        static void Main()
        {
            var graph = new Dictionary<int, List<int>>();
            int f = int.Parse(Console.ReadLine());
            int k = int.Parse(Console.ReadLine());

            for (int i = 0; i < f; i++)
            {
                int[] edge = new int[2];
                edge =
                    Console.ReadLine()
                        .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(int.Parse)
                        .ToArray();
                if (!graph.ContainsKey(edge[0]))
                {
                    graph[edge[0]] = new List<int>();
                }

                graph[edge[0]].Add(edge[1]);

                if (!graph.ContainsKey(edge[1]))
                {
                    graph[edge[1]] = new List<int>();
                }

                graph[edge[1]].Add(edge[0]);
            }

            var currentNode = k;
            int count = FindLongestDance(graph, k);
            Console.WriteLine(count);
        }
开发者ID:AsenTahchiyski,项目名称:SoftUni,代码行数:33,代码来源:Program.cs

示例11: StackTraceElement

        /// <summary>
        /// Initializes a new instance of the <see cref="StackTraceElement"/> class using the given property values.
        /// </summary>
        /// <param name="elementAttributes">A <see cref="Dictionary{K, V}"/> containing the names and values for the properties of this <see cref="StackTraceElement"/>.</param>
        public StackTraceElement(Dictionary<string, object> elementAttributes)
        {
            if (elementAttributes != null)
            {
                if (elementAttributes.ContainsKey("className") && elementAttributes["className"] != null)
                {
                    this.className = elementAttributes["className"].ToString();
                }

                if (elementAttributes.ContainsKey("methodName") && elementAttributes["methodName"] != null)
                {
                    this.methodName = elementAttributes["methodName"].ToString();
                }

                if (elementAttributes.ContainsKey("lineNumber"))
                {
                    this.lineNumber = Convert.ToInt32(elementAttributes["lineNumber"], CultureInfo.InvariantCulture);
                }

                if (elementAttributes.ContainsKey("fileName") && elementAttributes["fileName"] != null)
                {
                    this.fileName = elementAttributes["fileName"].ToString();
                }
            }
        }
开发者ID:RanchoLi,项目名称:selenium,代码行数:29,代码来源:StackTraceElement.cs

示例12: EvaluateChain

        private static bool EvaluateChain(string chain)
        {
            var nodes = new Dictionary<string, string>();

            // Build LinkedList
            foreach (string pair in chain.Split(';'))
            {
                // Node value: node[0]
                // Next node:  node[1]
                var node = pair.Split('-');
                if (nodes.ContainsKey(node[0])) { return false; }   // Duplicate
                if (node[0].Equals(node[1])) { return false; }      // Cycle
                nodes.Add(node[0], node[1]);
            }

            // Evaluate LinkedList
            // 500 pairs, maximum therefore it is more effective to just iterate at max 500 instead of doing cycle detection.
            // The counter will also make sure that we fail, if we have unconnected nodes :)
            // BEGIN-3;3-4;4-2;2-END --> GOOD
            // BEGIN-3;3-4;4-2;2-3   --> BAD
            string transitionTo = "BEGIN";
            for (int i = 0; i < nodes.Count; i++)
            {
                if (!nodes.ContainsKey(transitionTo)) { return false; }
                transitionTo = nodes[transitionTo];
            }

            // At the end, transitionTo should be Pointing to END
            return transitionTo.Equals("END");
        }
开发者ID:joshimoo,项目名称:Challenges,代码行数:30,代码来源:ChainInspection.cs

示例13: FiltrateFighters

 public void FiltrateFighters()
 {
     var pretendents = new Dictionary<string, int>();
     foreach (var e in Fighters)
         if (!pretendents.ContainsKey(e.Item1))
             pretendents[e.Item1] = 0;
     var temp = pretendents.ToDictionary(x => x.Key, y => y.Value);
     foreach (var e in temp)
     {
         try
         {
             var process = new Process();
             process.StartInfo.FileName = "Checkers.Tournament.exe";
             process.StartInfo.Arguments = e.Key + " " + "testPlayer.dll";
             process.StartInfo.UseShellExecute = false;
             process.StartInfo.RedirectStandardInput = true;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.CreateNoWindow = true;
             process.Start();
             var winner = process.StandardOutput.ReadLine()[0];
             if (winner == 'W')
                 pretendents[e.Key]++;
         }
         catch
         {
             pretendents[e.Key] = -10;
         }
     }
     Fighters = Fighters.Where(x => pretendents.ContainsKey(x.Item1) && pretendents.ContainsKey(x.Item2))
                        .ToList();
     //добавить ограничение по победам
     // фильтруем некорректные дллс
 }
开发者ID:BandW404,项目名称:checkers,代码行数:33,代码来源:Program.cs

示例14: FillFromDictionary

 public override void FillFromDictionary(Dictionary<string, object> dict)
 {
     if(dict.ContainsKey("status")) {
         if(dict["status"] != null) {
             status = DataType.Instance.FillString(dict["status"]);
         }
     }
     if(dict.ContainsKey("date_created")) {
         if(dict["date_created"] != null) {
             date_created = DataType.Instance.FillDateTime(dict["date_created"]);
         }
     }
     if(dict.ContainsKey("active")) {
         if(dict["active"] != null) {
             active = DataType.Instance.FillBool(dict["active"]);
         }
     }
     if(dict.ContainsKey("uuid")) {
         if(dict["uuid"] != null) {
             uuid = DataType.Instance.FillString(dict["uuid"]);
         }
     }
     if(dict.ContainsKey("date_modified")) {
         if(dict["date_modified"] != null) {
             date_modified = DataType.Instance.FillDateTime(dict["date_modified"]);
         }
     }
 }
开发者ID:drawcode,项目名称:bom,代码行数:28,代码来源:BaseEntity.cs

示例15: ParseOAuthCallbackUrl

        public virtual FacebookOAuthResult ParseOAuthCallbackUrl(Uri uri)
        {
            var parameters = new Dictionary<string, object>();

            bool found = false;
            if (!string.IsNullOrEmpty(uri.Fragment))
            {
                // #access_token and expries_in are in fragment
                var fragment = uri.Fragment.Substring(1);
                ParseUrlQueryString("?" + fragment, parameters, true);

                if (parameters.ContainsKey("access_token"))
                    found = true;
            }

            // code, state, error_reason, error and error_description are in query
            // ?error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.
            var queryPart = new Dictionary<string, object>();
            ParseUrlQueryString(uri.Query, queryPart, true);

            if (queryPart.ContainsKey("code") || (queryPart.ContainsKey("error") && queryPart.ContainsKey("error_description")))
                found = true;

            foreach (var kvp in queryPart)
                parameters[kvp.Key] = kvp.Value;

            if (found)
                return new FacebookOAuthResult(parameters);

            throw new InvalidOperationException("Could not parse Facebook OAuth url.");
        }
开发者ID:amartyamandal,项目名称:facebook-csharp-sdk,代码行数:31,代码来源:FacebookClient.OAuthResult.cs


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