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


C# Dictionary.GetOrDefault方法代码示例

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


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

示例1: ToolAction

        public ToolAction(CodeGenerator codeGenerator, CodeGeneratorEntry entry, Dictionary<string, string> props)
        {
            this.CodeGenerator = codeGenerator;
            _props = props;
            this.Entry = entry;

            this.Comment = _props.GetOrDefault("comment");
            this.FileName = _props.GetOrDefault("file-name");
        }
开发者ID:taucode,项目名称:taucode,代码行数:9,代码来源:ToolAction.cs

示例2: ShouldBeAbleToGetADefaultValueIfTheKeyDoesntExist

        public void ShouldBeAbleToGetADefaultValueIfTheKeyDoesntExist()
        {
            DateTime theDate = DateTime.Parse("April 04, 2005");
            DateTime defaultDate = DateTime.Parse("October 31, 2005");

            var bag = new Dictionary<string, object>();
            Assert.That(bag.GetOrDefault("some_date", defaultDate), Is.EqualTo(defaultDate));

            bag.Add("some_date", theDate);
            Assert.That(bag.GetOrDefault("some_date", defaultDate), Is.EqualTo(theDate));
        }
开发者ID:JonKruger,项目名称:MvcContrib,代码行数:11,代码来源:ViewDataExtensionsForIDictionaryTester.cs

示例3: GetOrDefaultPresent

        public void GetOrDefaultPresent()
        {
            Dictionary<string, int> dict = new Dictionary<string, int>() { { "one", 1 } };

            int value = dict.GetOrDefault("one", -999);

            Assert.Equal(1, 1);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:8,代码来源:DictionaryHelpersTest.cs

示例4: GetOrDefaultMissing

        public void GetOrDefaultMissing()
        {
            Dictionary<string, int> dict = new Dictionary<string, int>();
            int @default = 15;

            int value = dict.GetOrDefault("two", @default);

            Assert.Equal(15, @default);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:9,代码来源:DictionaryHelpersTest.cs

示例5: QuestionCreateor

 private static Func<Question, RichQuestion> QuestionCreateor(Dictionary<int, int> votes,
                                                              Dictionary<int, int> answerCounts)
 {
     return q => new RichQuestion(q,
                                  votes.GetOrDefault(q.Id),
                                  null,
                                  null,
                                  answerCounts.GetOrDefault(q.Id));
 }
开发者ID:RickIsWright,项目名称:Stack-Underflow,代码行数:9,代码来源:RichQuestionRepository.cs

示例6: Value_Not_Exists

        public void Value_Not_Exists()
        {
            var key = "key";

            Dictionary<string, object> target = new Dictionary<string, object>();
            var actual = target.GetOrDefault(key);

            Assert.IsNull(actual);
        }
开发者ID:jacktsai,项目名称:ERP_API,代码行数:9,代码来源:DictionaryExtensionsUnitTest.cs

示例7: MatchNode

		PositionedNode MatchNode(PositionedNode oldNode, Dictionary<int, PositionedNode> newNodeMap)
		{
			PositionedNode newNodeFound = newNodeMap.GetOrDefault(oldNode.ObjectNode.HashCode);
			if ((newNodeFound != null) && IsSameAddress(oldNode, newNodeFound))	{
				return newNodeFound;
			} else {
				return null;
			}
		}
开发者ID:Paccc,项目名称:SharpDevelop,代码行数:9,代码来源:GraphMatcher.cs

示例8: Value_Is_Null

        public void Value_Is_Null()
        {
            var key = "key";

            Dictionary<string, object> target = new Dictionary<string, object>();
            target.Add(key, null);
            var actual = target.GetOrDefault(key);

            Assert.IsNull(actual);
        }
开发者ID:jacktsai,项目名称:ERP_API,代码行数:10,代码来源:DictionaryExtensionsUnitTest.cs

示例9: Value_Exists

        public void Value_Exists()
        {
            var key = "key";
            var expected = "hello world!";

            Dictionary<string, object> target = new Dictionary<string, object>();
            target.Add(key, expected);
            var actual = target.GetOrDefault(key);

            Assert.AreEqual(expected, actual);
        }
开发者ID:jacktsai,项目名称:ERP_API,代码行数:11,代码来源:DictionaryExtensionsUnitTest.cs

示例10: Main

    /* 3 Write a program that finds a set of words (e.g. 1000 words)
     * in a large text (e.g. 100 MB text file). Print how many times
     * each word occurs in the text.
     * Hint: you may find a C# trie in Internet.
     * */
    static void Main(string[] args)
    {
        var dict = new Dictionary<string, int>();
        var knownCount = new Dictionary<string, int>
        {
            {"foo", 10*1000},
            {"bar", 20*1000},
            {"quux",30*1000},
            {"frob",40*1000},
            {"asdf",50*1000}
        };
        var trie = new Trie<int>();

        var sw = new Stopwatch();

        sw.Start();

        // obviously, I couldn't zip the 100 MB file
        // use "bin\debug\generator.cs" to generate it if you want

        using (var reader = new StreamReader("text.txt"))
            foreach (var word in Words(reader))
                dict[word] = 1 + dict.GetOrDefault(word, 0);

        sw.Stop();
        /*
        foreach (var kvp in knownCount)
            Debug.Assert(dict[kvp.Key] == kvp.Value);
        */

        Console.WriteLine("Using hashtable: " + sw.Elapsed.TotalMilliseconds);

        sw.Reset();
        sw.Start();

        using (var reader = new StreamReader("text.txt"))
            foreach (var word in Words(reader))
                trie.Add(word, 1 + trie.GetOrDefault(word, 0));

        sw.Stop();

        foreach (var kvp in dict)
            Debug.Assert(trie.Find(kvp.Key) == kvp.Value);

        // the trie would probably do much better compared to a hashtable when used on
        // natural text with large amount of repetition and low average word length
        // it is however extremely space inefficient

        // at any rate, I'd be surprised if this implementation could beat .NET's build-in
        // hashtable

        Console.WriteLine("Using trie: " + sw.Elapsed.TotalMilliseconds);
    }
开发者ID:staafl,项目名称:ta-hw-dsa,代码行数:58,代码来源:program.cs

示例11: DeleteMappedResultsForDocumentId

		public void DeleteMappedResultsForDocumentId(string documentId, string view, Dictionary<ReduceKeyAndBucket, int> removed)
		{
			foreach (var key in storage.MappedResults["ByViewAndDocumentId"].SkipTo(new RavenJObject
			{
				{"view", view},
				{"docId", documentId}
			}).TakeWhile(x => StringComparer.OrdinalIgnoreCase.Equals(x.Value<string>("view"), view) &&
							  StringComparer.OrdinalIgnoreCase.Equals(x.Value<string>("docId"), documentId)))
			{
				storage.MappedResults.Remove(key);

				var reduceKey = key.Value<string>("reduceKey");
				var bucket = new ReduceKeyAndBucket(key.Value<int>("bucket"), reduceKey);
				removed[bucket] = removed.GetOrDefault(bucket) + 1;
			}
		}
开发者ID:robashton,项目名称:ravendb,代码行数:16,代码来源:MappedResultsStorageAction.cs

示例12: Build

        public static string Build(IEnumerable<AssemblyDefinition> assemblys, string outDirectory, string bridgeDllPath, string libWhite, string libBlack) {
            TypeDefinitionBuilder builder = new TypeDefinitionBuilder(libWhite, libBlack);
            List<CodeCompileUnit> units = new List<CodeCompileUnit>();

            foreach(var assemblyDefinition in assemblys) {
                CodeCompileUnit unit = new CodeCompileUnit();
                Dictionary<string, CodeNamespace> namespaces = new Dictionary<string, CodeNamespace>();
                foreach(var module in assemblyDefinition.Modules) {
                    foreach(var type in module.Types) {
                        if(builder.IsEnableType(type)) {
                            CodeTypeDeclaration codeTypeDeclaration = builder.Build(type);
                            CodeNamespace codeNamespace = namespaces.GetOrDefault(type.Namespace);
                            if(codeNamespace == null) {
                                codeNamespace = new CodeNamespace(type.Namespace);
                                namespaces.Add(codeNamespace.Name, codeNamespace);
                            }
                            codeNamespace.Types.Add(codeTypeDeclaration);
                        }
                    }
                }

                unit.Namespaces.AddRange(namespaces.Values.ToArray());
                units.Add(unit);
            }

            CompilerParameters cp = new CompilerParameters();
            cp.CoreAssemblyFileName = bridgeDllPath;
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = false;
            cp.TreatWarningsAsErrors = false;
            cp.TempFiles.KeepFiles = true;
            cp.OutputAssembly = Path.Combine(outDirectory, kWrapDllName);
            cp.ReferencedAssemblies.Add(bridgeDllPath);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, units.Select(i => i.Compile()).ToArray());
            if(cr.Errors.Count > 0) {
                StringBuilder sb = new StringBuilder();
                foreach(CompilerError ce in cr.Errors) {
                    sb.AppendFormat(" {0}", ce.ToString());
                    sb.AppendLine();
                }
                throw new System.Exception(sb.ToString());
            }

            return cr.PathToAssembly;
        }
开发者ID:yindongfei,项目名称:bridge.lua,代码行数:47,代码来源:Wrap.cs

示例13: Generate

        public Core.Entity Generate(Core.EntitySet set, Resources.ResourceCache cache, string entityName, Dictionary<string, object> parameters)
        {
            var e = set.Create(entityName);

            var sprite = e.AddComponent<Sprite>();
            if (r == null)
                r = new Random((int)(DateTime.Now.Ticks % (long)int.MaxValue));
            var path = "Data/Texture/house" + r.Next(500) % (MaxIndex + 1) + ".png";
            sprite.Load(cache, path);
            sprite.Origin = new SharpDX.Vector2(160f / 2f);

            var rot = parameters.GetOrDefault("Rotation", 0f);
            e.Transform.LocalRotation = rot;

            var area = e.AddComponent<ClickArea>();
            area.BaseWidth = 160;
            area.BaseHeight = 160;
            area.OriginX = sprite.Origin.X;
            area.OriginY = sprite.Origin.Y;

            return e;
        }
开发者ID:quandtm,项目名称:Capstone,代码行数:22,代码来源:HouseEntity.cs

示例14: DeleteMappedResultsForDocumentId

		public void DeleteMappedResultsForDocumentId(string documentId, string view, Dictionary<ReduceKeyAndBucket, int> removed)
		{
			Api.JetSetCurrentIndex(session, MappedResults, "by_view_and_doc_key");
			Api.MakeKey(session, MappedResults, view, Encoding.Unicode, MakeKeyGrbit.NewKey);
			Api.MakeKey(session, MappedResults, documentId, Encoding.Unicode, MakeKeyGrbit.None);
			if (Api.TrySeek(session, MappedResults, SeekGrbit.SeekEQ) == false)
				return;

			Api.MakeKey(session, MappedResults, view, Encoding.Unicode, MakeKeyGrbit.NewKey);
			Api.MakeKey(session, MappedResults, documentId, Encoding.Unicode, MakeKeyGrbit.None);
			Api.JetSetIndexRange(session, MappedResults, SetIndexRangeGrbit.RangeUpperLimit | SetIndexRangeGrbit.RangeInclusive);
			do
			{
				// esent index ranges are approximate, and we need to check them ourselves as well
				var viewFromDb = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["view"]);
				if (StringComparer.OrdinalIgnoreCase.Equals(viewFromDb, view) == false)
					continue;
				var documentIdFromDb = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["document_key"]);
				if (StringComparer.OrdinalIgnoreCase.Equals(documentIdFromDb, documentId) == false)
					continue;
				var reduceKey = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["reduce_key"],
														   Encoding.Unicode);
				var bucket = Api.RetrieveColumnAsInt32(session, MappedResults, tableColumnsCache.MappedResultsColumns["bucket"]).Value;

				var key = new ReduceKeyAndBucket(bucket, reduceKey);
				removed[key] = removed.GetOrDefault(key) + 1;
				Api.JetDelete(session, MappedResults);
			} while (Api.TryMoveNext(session, MappedResults));
		}
开发者ID:KyleGobel,项目名称:ravendb,代码行数:29,代码来源:MappedResults.cs

示例15: DeleteMappedResultsForDocumentId

		public void DeleteMappedResultsForDocumentId(string documentId, int view, Dictionary<ReduceKeyAndBucket, int> removed)
		{
            var viewKey = CreateKey(view);
            var viewKeySlice = new Slice(viewKey);
			var viewAndDocumentId = new Slice(AppendToKey(viewKey, documentId));

            var mappedResultsByViewAndDocumentId = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndDocumentId);
            var mappedResultsByView = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByView);
            var mappedResultsByViewAndReduceKey = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndReduceKey);
            var mappedResultsByViewAndReduceKeyAndSourceBucket = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndReduceKeyAndSourceBucket);
            var mappedResultsData = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.Data);

			using (var iterator = mappedResultsByViewAndDocumentId.MultiRead(Snapshot, viewAndDocumentId))
			{
				if (!iterator.Seek(Slice.BeforeAllKeys))
					return;

				do
				{
					// TODO: Check if we can relax the clone.
                    var id = iterator.CurrentKey.Clone();

					ushort version;
					var value = LoadStruct(tableStorage.MappedResults, id, writeBatch.Value, out version);
					var reduceKey = value.ReadString(MappedResultFields.ReduceKey);
					var bucket = value.ReadInt(MappedResultFields.Bucket);

                    var reduceKeyHash = HashKey(reduceKey);                  
                    var viewAndReduceKey = AppendToKey(viewKey, ReduceKeySizeLimited(reduceKey), reduceKeyHash);
                    var viewAndReduceKeyAndSourceBucket = AppendToKey(viewAndReduceKey, bucket);

                    tableStorage.MappedResults.Delete(writeBatch.Value, id);

                    mappedResultsByViewAndDocumentId.MultiDelete(writeBatch.Value, viewAndDocumentId, id);
                    mappedResultsByView.MultiDelete(writeBatch.Value, viewKeySlice, id);
                    mappedResultsByViewAndReduceKey.MultiDelete(writeBatch.Value, (Slice)viewAndReduceKey, id);
                    mappedResultsByViewAndReduceKeyAndSourceBucket.MultiDelete(writeBatch.Value, (Slice)viewAndReduceKeyAndSourceBucket, id);
                    mappedResultsData.Delete(writeBatch.Value, id);

					var reduceKeyAndBucket = new ReduceKeyAndBucket(bucket, reduceKey);
					removed[reduceKeyAndBucket] = removed.GetOrDefault(reduceKeyAndBucket) + 1;
				}
				while (iterator.MoveNext());
			}
		}
开发者ID:jrusbatch,项目名称:ravendb,代码行数:45,代码来源:MappedResultsStorageActions.cs


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