本文整理汇总了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"));
}
示例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));
}
示例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"});
}
示例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);
}
示例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");
}
示例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);
}
示例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"]);
}
示例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.");
}
示例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);
}
示例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;
}
示例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;
}
示例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);
}
}
示例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;
}
示例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"));
}
示例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;
}