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


C# Dictionary.ForEach方法代码示例

本文整理汇总了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);
        }
开发者ID:HEskandari,项目名称:FarsiLibrary,代码行数:10,代码来源:CollectionExtensionTests.cs

示例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;
        }
开发者ID:Csad,项目名称:Senior-Project,代码行数:11,代码来源:ApiResponse.cs

示例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());
        }
开发者ID:cgavieta,项目名称:WORKPAC2016-poc,代码行数:13,代码来源:IEnumerableExtensionsTests.cs

示例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);
        }
开发者ID:einsteinsci,项目名称:ultimate-util,代码行数:23,代码来源:FluidUtil_Test.cs

示例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)));
        }
开发者ID:pb0,项目名称:ID0_Test,代码行数:15,代码来源:Grammar.cs

示例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);
        }
开发者ID:greendogs,项目名称:Transfluent-Unity,代码行数:44,代码来源:KeyStoreTest.cs

示例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];
     });
 }
开发者ID:pele1250,项目名称:SideNotes,代码行数:20,代码来源:MainWindowHandle2.cs

示例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);
                }
            }
        }
开发者ID:xeno-by,项目名称:elf4b,代码行数:41,代码来源:VaultEval.cs

示例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);
    }
开发者ID:fgeraci,项目名称:CS195-Core,代码行数:21,代码来源:SpaceData.cs

示例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();
            };
        }
开发者ID:Zaid-Ajaj,项目名称:LindenmayerSystems,代码行数:21,代码来源:LSystemVisualizer.cs

示例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.");
 }
开发者ID:pele1250,项目名称:SideNotes,代码行数:22,代码来源:StickyPersist.cs

示例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.");
            }
        }
开发者ID:BGCX261,项目名称:zmovies-svn-to-git,代码行数:23,代码来源:ConsoleQuestions.cs

示例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);
        }
开发者ID:simonproctor,项目名称:Glass.Sitecore.Mapper,代码行数:24,代码来源:AttributeConfigurationLoader.cs

示例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;
        }
开发者ID:Krave-n,项目名称:ServiceStack,代码行数:71,代码来源:AuthProvider.cs

示例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;
        }
开发者ID:DeepakRajendranMsft,项目名称:autorest,代码行数:91,代码来源:OperationBuilder.cs


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