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


C# Dictionary.GetOrAdd方法代码示例

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


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

示例1: Dictionary_GetOrAdd_Adds_Unexisting_Key

        public void Dictionary_GetOrAdd_Adds_Unexisting_Key()
        {
            var dictionary = new Dictionary<int, string>();

            Assert.Equal("test", dictionary.GetOrAdd(1, v => "test"));
            Assert.Equal("test", dictionary.GetOrAdd(1, v => "test2"));
        }
开发者ID:kcornelis,项目名称:FreelanceManager.NET,代码行数:7,代码来源:ExtensionsTests.cs

示例2: DebugIfNeeded

        public static void DebugIfNeeded(List<IObject> displayList)
        {
            string behindThis = _behindThis;
            if (behindThis == null) return;
            string whyIsThis = _whyIsThis;
            bool renderDebug = _renderDebug;
            _behindThis = null;

            Dictionary<string, List<string>> map = new Dictionary<string, List<string>>();
            const string sortWord = "Sort ";
            const string backwardsWord = "backwards ";
            foreach (var obj in displayList)
            {                
                foreach (var property in obj.Properties.Ints.AllProperties())
                {
                    if (!property.Key.Contains(sortWord)) continue;
                    if (renderDebug && property.Key.Contains(backwardsWord)) continue;
                    if (!renderDebug && !property.Key.Contains(backwardsWord)) continue;

                    string comparedId = property.Key.Substring(renderDebug ? property.Key.IndexOf(sortWord) + sortWord.Length : 
                        property.Key.IndexOf(backwardsWord) + backwardsWord.Length);

                    if (property.Value > 0) map.GetOrAdd(comparedId, () => new List<string>()).Add(obj.ID);
                    else map.GetOrAdd(obj.ID, () => new List<string>()).Add(comparedId);
                }
            }
            string chain = getChain(whyIsThis, behindThis, map, new HashSet<string>());
            Debug.WriteLine(chain == null ? string.Format("{0} is not behind {1}", whyIsThis, behindThis) :
                string.Format("{0}{1}", whyIsThis, chain));
        }
开发者ID:tzachshabtay,项目名称:MonoAGS,代码行数:30,代码来源:SortDebugger.cs

示例3: TestGetOrAdd

        public void TestGetOrAdd()
        {
            var dict = new Dictionary<string, string>();
            dict.GetOrAdd("x", () => "a");
            dict.GetOrAdd("x", () => { throw new Exception("Should not be reached."); });

            dict.Should().Equal(new Dictionary<string, string> {["x"] = "a"});
        }
开发者ID:nano-byte,项目名称:common,代码行数:8,代码来源:DictionaryExtensionsTest.cs

示例4: WhenGettingTwice_ThenGetsExisting

	public void WhenGettingTwice_ThenGetsExisting()
	{
		var dictionary = new Dictionary<string, Guid>();

		var value = dictionary.GetOrAdd("foo", key => Guid.NewGuid());
		var value2 = dictionary.GetOrAdd("foo", key => Guid.NewGuid());
		
		Assert.Equal(value, value2);
	}
开发者ID:netfx,项目名称:extensions,代码行数:9,代码来源:DictionaryGetOrAddSpec.cs

示例5: GetOrAdd

        public void GetOrAdd()
        {
            var dictionary = new Dictionary<int, string> { { 0, "Zero" } };

            dictionary.GetOrAdd(0, "0").ShouldBe("Zero");
            dictionary.GetOrAdd(1, "One").ShouldBe("One");
            dictionary.GetOrAdd(2, () => "Two").ShouldBe("Two");
            dictionary.GetOrAdd(3, i => i.ToString()).ShouldBe("3");
        }
开发者ID:JonasSamuelsson,项目名称:Handyman,代码行数:9,代码来源:DictionaryExtensionsTests.cs

示例6: TestMiscDictionaryGetOrAdd

        public void TestMiscDictionaryGetOrAdd()
        {
            string key0 = "Blinky";

            var dict = new Dictionary<string, int>();

            int value0 = 0;
            dict.GetOrAdd(key0, v => value0 = v, () => 42);
            Assert.Equal(0, value0);
            dict.GetOrAdd(key0, v => value0 = v, () => 42);
            Assert.Equal(42, value0);
        }
开发者ID:speps,项目名称:Parler,代码行数:12,代码来源:MiscTests.cs

示例7: GetOrAddTest

        public void GetOrAddTest()
        {
            var stringValues = new Dictionary<string, string>
            {
                ["key1"] = "Hoge"
            };

            Assert.AreEqual("Hoge", stringValues.GetOrAdd("key1", key => "Fuga"));
            Assert.AreEqual("Hoge", stringValues["key1"]);

            Assert.AreEqual("key2_Piyo", stringValues.GetOrAdd("key2", key => key + "_Piyo"));
            Assert.AreEqual("key2_Piyo", stringValues["key2"]);
        }
开发者ID:ysp2000,项目名称:ToggleComment,代码行数:13,代码来源:DictionaryExtensionsTest.cs

示例8: GetOrAdd

        public void GetOrAdd()
        {
            var d = new Dictionary<string, StockStatus>() {
                {"AAPL", new StockStatus { Price = 530.12m, Position = "Sell" }},
                {"GOOG", new StockStatus { Price = 123.5m, Position = "Buy" }}
            };

            d.GetOrAdd("AAPL").Position = "Buy";
            d.GetOrAdd("YHOO").Price = 1.99m;
            Console.Out.WriteLine(d.ToString<string, StockStatus>());

            Assert.That(d["AAPL"].Position, Is.EqualTo("Buy"), "Incorrect position.");
            Assert.That(d.Keys, Has.Count.EqualTo(3), "Incorrect number of keys.");
            Assert.That(d["YHOO"].Price, Is.EqualTo(1.99m), "Incorrect price.");
        }
开发者ID:tbashore,项目名称:TLib.NET,代码行数:15,代码来源:DictionaryTests.cs

示例9: GetOrAdd

        public void GetOrAdd()
        {
            // Type
            var @this = new Dictionary<string, string>();

            // Examples
            string value1 = @this.GetOrAdd("Fizz", "Buzz"); // return "Buzz";
            string value2 = @this.GetOrAdd("Fizz", "Buzz2"); // return "Buzz"; // The Dictionary already contains the key
            string value3 = @this.GetOrAdd("Fizz2", s => "Buzz"); // return "Buzz";

            // Unit Test
            Assert.AreEqual("Buzz", value1);
            Assert.AreEqual("Buzz", value2);
            Assert.AreEqual("Buzz", value3);
        }
开发者ID:ChuangYang,项目名称:Z.ExtensionMethods,代码行数:15,代码来源:IDictionary[TKey,TValue].GetOrAdd.cs

示例10: Load

 public IEnumerable<RemoteInfo> Load(IEnumerable<ConfigurationEntry> config)
 {
     var remotes = new Dictionary<string, RemoteInfo>();
     foreach (var entry in config)
     {
         var keyParts = entry.Key.Split('.');
         if (keyParts.Length == 3 && keyParts[0] == "tfs-remote")
         {
             var id = keyParts[1];
             var key = keyParts[2];
             var remote = remotes.GetOrAdd(id);
             remote.Id = id;
             if (key == "url")
                 remote.Url = entry.Value;
             else if (key == "repository")
                 remote.Repository = entry.Value;
             else if (key == "username")
                 remote.Username = entry.Value;
             else if (key == "password")
                 remote.Password = entry.Value;
             else if (key == "ignore-paths")
                 remote.IgnoreRegex = entry.Value;
             else if (key == "legacy-urls")
                 remote.Aliases = entry.Value.Split(',');
             else if (key == "autotag")
                 remote.Autotag = bool.Parse(entry.Value);
         }
     }
     return remotes.Values;
 }
开发者ID:runt18,项目名称:git-tfs,代码行数:30,代码来源:RemoteConfigConverter.cs

示例11: AddNewErrors

        public int AddNewErrors(IVsEnumExternalErrors pErrors)
        {
            var projectErrors = new HashSet<DiagnosticData>();
            var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>();

            var errors = new ExternalError[1];
            uint fetched;
            while (pErrors.Next(1, errors, out fetched) == VSConstants.S_OK && fetched == 1)
            {
                var error = errors[0];

                DiagnosticData diagnostic;
                if (error.bstrFileName != null)
                {
                    diagnostic = CreateDocumentDiagnosticItem(error);
                    if (diagnostic != null)
                    {
                        var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>());
                        diagnostics.Add(diagnostic);
                        continue;
                    }

                    projectErrors.Add(CreateProjectDiagnosticItem(error));
                }
                else
                {
                    projectErrors.Add(CreateProjectDiagnosticItem(error));
                }
            }

            _diagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap);
            return VSConstants.S_OK;
        }
开发者ID:swaroop-sridhar,项目名称:roslyn,代码行数:33,代码来源:ProjectExternalErrorReporter.cs

示例12: GlobalCache

            public GlobalCache(Dictionary<IAdapter, Consumer> consumers, int version)
            {
                GlobalSignalLookup = new Dictionary<Guid, List<Consumer>>();
                GlobalDestinationLookup = consumers;
                BroadcastConsumers = new List<Consumer>();
                Version = version;

                // Generate routes for all signals received by each consumer adapter
                foreach (var kvp in consumers)
                {
                    var consumerAdapter = kvp.Key;
                    var consumer = kvp.Value;

                    if ((object)consumerAdapter.InputMeasurementKeys != null)
                    {
                        // Create routes for each of the consumer's input signals
                        foreach (Guid signalID in consumerAdapter.InputMeasurementKeys.Select(key => key.SignalID))
                        {
                            GlobalSignalLookup.GetOrAdd(signalID, id => new List<Consumer>()).Add(consumer);
                        }
                    }
                    else
                    {
                        // Add this consumer to the broadcast routes to begin receiving all measurements
                        BroadcastConsumers.Add(consumer);
                    }
                }

                // Broadcast consumers receive all measurements, so add them to every signal route
                foreach (List<Consumer> consumerList in GlobalSignalLookup.Values)
                {
                    consumerList.AddRange(BroadcastConsumers);
                }
            }
开发者ID:rmc00,项目名称:gsf,代码行数:34,代码来源:RouteMappingDoubleBufferQueue.cs

示例13: Load

 public IEnumerable<RemoteInfo> Load(IEnumerable<ConfigurationEntry<string>> config)
 {
     var remotes = new Dictionary<string, RemoteInfo>();
     foreach (var entry in config)
     {
         var keyParts = entry.Key.Split('.');
         if (keyParts.Length >= 3 && keyParts[0] == "tfs-remote")
         {
             // The branch name may contain dots ("maint-1.0.0") which must be considered since split on "."
             var id = string.Join(".", keyParts, 1, keyParts.Length - 2);
             var key = keyParts.Last();
             var remote = remotes.GetOrAdd(id);
             remote.Id = id;
             if (key == "url")
                 remote.Url = entry.Value;
             else if (key == "repository")
                 remote.Repository = entry.Value;
             else if (key == "username")
                 remote.Username = entry.Value;
             else if (key == "password")
                 remote.Password = entry.Value;
             else if (key == "ignore-paths")
                 remote.IgnoreRegex = entry.Value;
             else if (key == "legacy-urls")
                 remote.Aliases = entry.Value.Split(',');
             else if (key == "autotag")
                 remote.Autotag = bool.Parse(entry.Value);
         }
     }
     return remotes.Values;
 }
开发者ID:abezzub,项目名称:git-tfs,代码行数:31,代码来源:RemoteConfigConverter.cs

示例14: Dictionary_GetOrAdd_Gets_An_Existing_Value

        public void Dictionary_GetOrAdd_Gets_An_Existing_Value()
        {
            var dictionary = new Dictionary<int, string>();
            dictionary.Add(1, "1");

            Assert.Equal("1", dictionary.GetOrAdd(1, v => "test"));
        }
开发者ID:kcornelis,项目名称:FreelanceManager.NET,代码行数:7,代码来源:ExtensionsTests.cs

示例15: CreateOldToNewTokensMap

            private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap(
                Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs,
                Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs)
            {
                var map = new Dictionary<SyntaxToken, SyntaxToken>();
                foreach (var pair in CreateUniqueTokenTriviaPairs(tokenPairs, triviaPairs))
                {
                    var localCopy = pair;
                    var previousToken = map.GetOrAdd(localCopy.Item1.PreviousToken, _ => localCopy.Item1.PreviousToken);
                    map[localCopy.Item1.PreviousToken] = previousToken.WithTrailingTrivia(localCopy.Item2.TrailingTrivia);

                    var nextToken = map.GetOrAdd(localCopy.Item1.NextToken, _ => localCopy.Item1.NextToken);
                    map[localCopy.Item1.NextToken] = nextToken.WithLeadingTrivia(localCopy.Item2.LeadingTrivia);
                }

                return map;
            }
开发者ID:GloryChou,项目名称:roslyn,代码行数:17,代码来源:AbstractSyntaxTriviaService.Result.cs


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