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