本文整理汇总了C#中Dictionary.ForEach方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.ForEach方法的具体用法?C# Dictionary.ForEach怎么用?C# Dictionary.ForEach使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Dictionary
的用法示例。
在下文中一共展示了Dictionary.ForEach方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Can_Use_ForEach_On_Dictionaries
public void Can_Use_ForEach_On_Dictionaries()
{
var dictionary = new Dictionary<string, string>();
var i = 0;
dictionary.Add("John", "Doe");
dictionary.ForEach(o => i++);
Assert.AreEqual(1, i);
}
示例2: GenerateResponse
public HttpResponseMessage GenerateResponse(HttpStatusCode code, Dictionary<string, string> headers = null)
{
HttpResponseMessage res = request.CreateResponse(code, data ?? errors);
if (headers != null)
{
headers.ForEach(header => res.Headers.Add(header.Key, header.Value));
}
return res;
}
示例3: ForEachDictionary
public void ForEachDictionary()
{
Dictionary<string, string> dict = new Dictionary<string, string>
{
{ "foo", "bar" },
{ "baz", "qux" }
};
StringBuilder builder = new StringBuilder();
dict.ForEach(kvp => builder.Append(kvp.Value));
Assert.AreEqual("barqux", builder.ToString());
}
示例4: ForEachDict
public void ForEachDict()
{
string res = "";
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{ "a", "1" },
{ "b", "2" },
{ "c", "3" }
};
dict.ForEach((k, v) =>
{
res += k + "=" + v + ";";
});
Assert.AreEqual("a=1;b=2;c=3;", res);
res = "";
dict.ForEach((k, v) =>
{
res += k + "^" + v + " ";
});
Assert.AreEqual("a^1 b^2 c^3 ", res);
}
示例5: Grammar
static Grammar()
{
keywords = new Dictionary<SyntacticPart, IEnumerable<string>>();
keywords.Add(SyntacticPart.ActionName, ArrayTool.Create("Action", "Motion", "Projectile"));
keywords.Add(SyntacticPart.BraceOpen, ArrayTool.Create("{"));
keywords.Add(SyntacticPart.BraceClose, ArrayTool.Create("}"));
keywords.Add(SyntacticPart.ParenOpen, ArrayTool.Create("("));
keywords.Add(SyntacticPart.ParenClose, ArrayTool.Create(")"));
keywords.Add(SyntacticPart.If, ArrayTool.Create("if"));
keywords.Add(SyntacticPart.Else, ArrayTool.Create("else"));
keywords.Add(SyntacticPart.Semicolon, ArrayTool.Create(";"));
textToPart = new Dictionary<string, SyntacticPart>();
keywords.ForEach(x => x.Value.ForEach(y => textToPart.Add(y, x.Key)));
}
示例6: testEqualityOfInMemoryDictionary
public void testEqualityOfInMemoryDictionary()
{
var randomvalues = new Dictionary<string, string>
{
{"KEYYYYYYY" + Random.value, "valuuuuuuuueeeee" + Random.value},
{"chunky" + Random.value, "monkey" + Random.value},
{"that " + Random.value, "funky" + Random.value},
{"1234", "5678"},
{"abc", "def"},
};
var inMemory = new InMemoryKeyStore();
var playerprefs = new PlayerPrefsKeyStore();
var editor = new EditorKeyStore();
var values = new List<string>();
randomvalues.ForEach((KeyValuePair<string, string> kvp) => { values.Add(kvp.Value); });
string valueStringNewlineDelimited = string.Join("\n", values.ToArray());
var fileProvider = new FileLineBasedKeyStore(getMemoryStream(valueStringNewlineDelimited), values);
Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(inMemory));
Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(playerprefs));
Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(editor));
Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(fileProvider));
foreach(var kvp in randomvalues)
{
Debug.Log("Setting kvp:" + kvp.Key + " val" + kvp.Value);
inMemory.set(kvp.Key, kvp.Value);
playerprefs.set(kvp.Key, kvp.Value);
editor.set(kvp.Key, kvp.Value);
fileProvider.set(kvp.Key, kvp.Value);
}
standardCheck(inMemory, dictionary);
standardCheck(playerprefs, dictionary);
standardCheck(editor, dictionary);
standardCheck(fileProvider, dictionary);
Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(inMemory));
Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(playerprefs));
Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(editor));
Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(fileProvider));
var provider = new FileBasedCredentialProvider();
Assert.AreEqual(provider.username, "[email protected]");
Debug.Log("HELLO" + provider.username);
}
示例7: ApplyOptions
private void ApplyOptions(object sender, Dictionary<string, bool> options)
{
logger.Info("Applying new options.");
options.ForEach((option) =>
{
if (option.Key == OptionStore.MINIMIZE_ON_CLOSE)
{
window.cbMinimizeOnClose.IsChecked = option.Value;
}
else if (option.Key == OptionStore.SHOW_CONFIRMATIONS)
{
window.cbShowConfirm.IsChecked = option.Value;
}
else if (option.Key == OptionStore.START_WITH_WINDOWS)
{
window.cbStartWithWindows.IsChecked = option.Value;
}
shouldClose = !optionStore.Options[OptionStore.MINIMIZE_ON_CLOSE];
});
}
示例8: Eval
public static object Eval(this IBranch b, IVault repository)
{
try
{
AppDomain.CurrentDomain.Load("Esath.Data");
var ei = new ElfInteractive();
var stack = new List<Expression>();
var nodes = new Dictionary<String, IBranch>();
var expandedCode = ExpandRhs(b, repository, stack, nodes).RenderElfCode(null);
nodes.ForEach(kvp => ei.Ctx.Add(kvp.Key, kvp.Value));
return ei.Eval(expandedCode).Retval;
}
catch(BaseEvalException)
{
throw;
}
catch(ErroneousScriptRuntimeException esex)
{
if (esex.Type == ElfExceptionType.OperandsDontSuitMethod)
{
throw new ArgsDontSuitTheFunctionException(esex.Thread.RuntimeContext.PendingClrCall, esex);
}
else
{
throw new UnexpectedErrorException(esex);
}
}
catch(Exception ex)
{
if (ex.InnerException is FormatException)
{
throw new BadFormatOfSerializedStringException(ex);
}
else
{
throw new UnexpectedErrorException(ex);
}
}
}
示例9: EncodeEdges
private static IEnumerable<EdgeData> EncodeEdges(
IList<ExplorationNode> nodes,
out Dictionary<ExplorationEdge, uint> edgeToId)
{
HashSet<ExplorationEdge> edgeSet = new HashSet<ExplorationEdge>();
foreach (ExplorationNode node in nodes)
{
node.OutgoingExploration.ForEach(e => edgeSet.Add(e));
node.IncomingExploration.ForEach(e => edgeSet.Add(e));
}
edgeToId = new Dictionary<ExplorationEdge, uint>();
uint edgeId = 0;
foreach (ExplorationEdge edge in edgeSet)
edgeToId[edge] = edgeId++;
List<EdgeData> edgeData = new List<EdgeData>();
edgeToId.ForEach(
(kv) => edgeData.Add(new EdgeData(kv.Value, kv.Key)));
return edgeData.OrderBy((data) => data.EdgeId);
}
示例10: LSystemVisualizer
public LSystemVisualizer()
{
InitializeComponent();
var ctxMenu = new ContextMenu();
var menuItem = new MenuItem("Save");
menuItem.Click += SavePicture;
ctxMenu.MenuItems.Add(menuItem);
picLSystem.ContextMenu = ctxMenu;
systems = Parser.LoadSystems();
systems.ForEach(sys => cboxSystems.Items.Add(sys.Key));
cboxSystems.SelectedIndex = 0;
btnDraw.Click += (sender, e) => Draw();
sliderGeneration.ValueChanged += (sender, e) =>
{
generation = sliderGeneration.Value;
label4.Text = $"N = {sliderGeneration.Value}";
Draw();
};
}
示例11: SaveStickies
public void SaveStickies(Dictionary<int, NoteWindow> stickies)
{
logger.Info("Attempting to save stickies.");
if (stickies == null || stickies.Count == 0)
{
logger.Info("There are no stickies to save.");;
File.Delete(fullPath);
return;
}
using (StreamWriter writer = new StreamWriter(fullPath))
{
stickies.ForEach((sticky) =>
{
StickyBase stickyBase = sticky.Value;
writer.WriteLine(@stickyBase.ToString().Replace("\n", "\\n").Replace("\r", "\\r"));
writer.Flush();
});
writer.Flush();
writer.Close();
}
logger.Info("Stickies successfully saved.");
}
示例12: AskSingle
public static string AskSingle(Dictionary<ConsoleKey, string> a)
{
a.ForEach(
(KeyValuePair<ConsoleKey, string> k, int i) =>
{
Console.WriteLine(" " + k.Key.ToString().Substring(1) + ". " + k.Value);
}
);
while (true)
{
var key = Console.ReadKey(true);
if (a.ContainsKey(key.Key))
{
Console.WriteLine(">>" + key.Key.ToString().Substring(1) + ". " + a[key.Key]);
return a[key.Key];
}
Console.WriteLine("Try again.");
}
}
示例13: Load
public override IEnumerable<SitecoreClassConfig> Load()
{
if (_namespaces == null || _namespaces.Count() == 0) return new List<SitecoreClassConfig>();
Dictionary<Type,SitecoreClassConfig> classes = new Dictionary<Type, SitecoreClassConfig>();
foreach (string space in _namespaces)
{
string[] parts = space.Split(',');
var namespaceClasses = GetClass(parts[1], parts[0]);
namespaceClasses.ForEach(cls =>
{
//stops duplicates being added
if (!classes.ContainsKey(cls.Type))
{
classes.Add(cls.Type, cls);
}
});
};
classes.ForEach(x => x.Value.Properties = GetProperties(x.Value.Type));
return classes.Select(x => x.Value);
}
示例14: OnAuthenticated
public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
var userSession = session as AuthUserSession;
if (userSession != null)
{
LoadUserAuthInfo(userSession, tokens, authInfo);
HostContext.TryResolve<IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
if (LoadUserAuthFilter != null)
{
LoadUserAuthFilter(userSession, tokens, authInfo);
}
}
var hasTokens = tokens != null && authInfo != null;
if (hasTokens)
{
authInfo.ForEach((x, y) => tokens.Items[x] = y);
}
var authRepo = authService.TryResolve<IAuthRepository>();
if (authRepo != null)
{
var failed = ValidateAccount(authService, authRepo, session, tokens);
if (failed != null)
return failed;
if (hasTokens)
{
session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
}
authRepo.LoadUserAuth(session, tokens);
foreach (var oAuthToken in session.ProviderOAuthAccess)
{
var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
if (authProvider == null) continue;
var userAuthProvider = authProvider as OAuthProvider;
if (userAuthProvider != null)
{
userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
}
}
var httpRes = authService.Request.Response as IHttpResponse;
if (session.UserAuthId != null && httpRes != null)
{
httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
}
}
else
{
if (hasTokens)
{
session.UserAuthId = CreateOrMergeAuthSession(session, tokens);
}
}
try
{
session.IsAuthenticated = true;
session.OnAuthenticated(authService, session, tokens, authInfo);
}
finally
{
authService.SaveSession(session, SessionExpiry);
}
return null;
}
示例15: BuildMethod
public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup)
{
EnsureUniqueMethodName(methodName, methodGroup);
var method = New<Method>(new
{
HttpMethod = httpMethod,
Url = url,
Name = methodName,
SerializedName = _operation.OperationId
});
method.RequestContentType = _effectiveConsumes.FirstOrDefault() ?? APP_JSON_MIME;
string produce = _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(produce))
{
method.RequestContentType = produce;
}
if (method.RequestContentType.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) &&
method.RequestContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
{
// Enable UTF-8 charset
method.RequestContentType += "; charset=utf-8";
}
method.Description = _operation.Description;
method.Summary = _operation.Summary;
method.ExternalDocsUrl = _operation.ExternalDocs?.Url;
method.Deprecated = _operation.Deprecated;
// Service parameters
if (_operation.Parameters != null)
{
BuildMethodParameters(method);
}
// Build header object
var responseHeaders = new Dictionary<string, Header>();
foreach (var response in _operation.Responses.Values)
{
if (response.Headers != null)
{
response.Headers.ForEach(h => responseHeaders[h.Key] = h.Value);
}
}
var headerTypeName = string.Format(CultureInfo.InvariantCulture,
"{0}-{1}-Headers", methodGroup, methodName).Trim('-');
var headerType = New<CompositeType>(headerTypeName,new
{
SerializedName = headerTypeName,
Documentation = string.Format(CultureInfo.InvariantCulture, "Defines headers for {0} operation.", methodName)
});
responseHeaders.ForEach(h =>
{
var property = New<Property>(new
{
Name = h.Key,
SerializedName = h.Key,
ModelType = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key),
Documentation = h.Value.Description
});
headerType.Add(property);
});
if (!headerType.Properties.Any())
{
headerType = null;
}
// Response format
List<Stack<IModelType>> typesList = BuildResponses(method, headerType);
method.ReturnType = BuildMethodReturnType(typesList, headerType);
if (method.Responses.Count == 0)
{
method.ReturnType = method.DefaultResponse;
}
if (method.ReturnType.Headers != null)
{
_swaggerModeler.CodeModel.AddHeader(method.ReturnType.Headers as CompositeType);
}
// Copy extensions
_operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value));
return method;
}