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


C# Dictionary.GetValueOrDefault方法代码示例

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


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

示例1: TestDictionary

        public void TestDictionary()
        {
            var d = new Dictionary<int, string> {{1, "one"}};
            Assert.AreEqual("one", d.GetValueOrDefault(1));
            Assert.AreEqual(null, d.GetValueOrDefault(2));

        }
开发者ID:raseesink,项目名称:ApprovalTests.Net,代码行数:7,代码来源:CollectionUtilsTest.cs

示例2: Release

 public Release(Dictionary<string,string> properties, DateTime date)
 {
     Title = properties.GetValueOrDefault("Title");
     ReleaseName = properties.GetValueOrDefault("Rlsname");
     Group = properties.GetValueOrDefault("Group");
     Tags = properties.GetValueOrDefault("Tags", string.Empty).Split(new char[] {','}).Select(str => str.Trim()).ToArray();
     Date = date;
 }
开发者ID:tomstaijen,项目名称:WatchlistTracker,代码行数:8,代码来源:PreDB.cs

示例3: GetValueOrDefaultReturnsValueFromDictionary

 public void GetValueOrDefaultReturnsValueFromDictionary()
 {
     var dictionary = new Dictionary<string, int> { { "one", 1 }, { "two", 2 }, { "three", 3 } };
     foreach (var pair in dictionary)
     {
         Assert.AreEqual(pair.Value, dictionary.GetValueOrDefault(pair.Key));
         Assert.AreEqual(pair.Value, dictionary.GetValueOrDefault(pair.Key, -1));
     }
 }
开发者ID:harold818,项目名称:unme,代码行数:9,代码来源:DictionaryUtilityTests.cs

示例4: ProcessStartElement

        public override void ProcessStartElement(string name, Dictionary<string, string> attributes)
        {
            base.ProcessStartElement(name, attributes);

              int port;
              Int32.TryParse(attributes.GetValueOrDefault("Port", String.Empty), out port);
              var newSmtpServer = new SmtpServer(attributes.GetValueOrDefault("Name", null), attributes.GetValueOrDefault("Host", null), port);
              MailManager.Instance.RegisterMailServer(newSmtpServer);
        }
开发者ID:BrightLight,项目名称:RepoCop,代码行数:9,代码来源:SmtpServerXmlHandler.cs

示例5: GetValueOrDefaultReturnsExpectedDefault

        public void GetValueOrDefaultReturnsExpectedDefault()
        {
            var colors = new Dictionary<ConsoleColor, string> { { ConsoleColor.Red, "Red" }, { ConsoleColor.Green, "Green" }, { ConsoleColor.Blue, "Blue" } };
            Assert.AreEqual(null, colors.GetValueOrDefault(ConsoleColor.DarkMagenta));
            Assert.AreEqual("not found!", colors.GetValueOrDefault(ConsoleColor.Magenta) ?? "not found!");

            var numbers = new Dictionary<string, int> { { "one", 1 }, { "two", 2 }, { "three", 3 } };
            Assert.AreEqual(0, numbers.GetValueOrDefault("four"));
            Assert.AreEqual(-1, numbers.GetValueOrDefault("five", -1));
        }
开发者ID:harold818,项目名称:unme,代码行数:10,代码来源:DictionaryUtilityTests.cs

示例6: TestGetValueOrDefault

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

            // Assert.
            Assert.AreEqual(1, dictionary.GetValueOrDefault("one", 0));

            Assert.AreEqual(0, dictionary.GetValueOrDefault("two"));
            Assert.AreEqual(0, dictionary.GetValueOrDefault("two", 0));
        }
开发者ID:ComanGames,项目名称:unity-query,代码行数:12,代码来源:CollectionsTests.cs

示例7: Init

 public override void Init(Dictionary<string, string> data)
 {
     if (data.ContainsKey("art"))
     {
         byte[] artfile = ObjectHelper.OpenArtFile(data["art"], (Compression.CompressionType)Enum.Parse(typeof(Compression.CompressionType), data.GetValueOrDefault("artcmp", "Nemesis")));
         if (data.ContainsKey("map"))
             img = ObjectHelper.MapToBmp(artfile, Compression.Decompress(data["map"], (Compression.CompressionType)Enum.Parse(typeof(Compression.CompressionType), data.GetValueOrDefault("mapcmp", "Uncompressed"))), int.Parse(data["frame"], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture), int.Parse(data.GetValueOrDefault("pal", "0"), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture));
         else if (data.ContainsKey("mapasm"))
             img = ObjectHelper.MapASMToBmp(artfile, data["mapasm"], data["mapasmlbl"], int.Parse(data.GetValueOrDefault("pal", "0"), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture));
     }
     spacing = int.Parse(data.GetValueOrDefault("spacing", "24"), System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo);
 }
开发者ID:OurSonic,项目名称:Sonic-Image-Parser,代码行数:12,代码来源:RingGroup.cs

示例8: ProcessStartElement

        public override void ProcessStartElement(string name, Dictionary<string, string> attributes)
        {
            base.ProcessStartElement(name, attributes);

              var tokenName = '#' + attributes.GetValueOrDefault("TokenName", string.Empty) + '#';
              var value = attributes.GetValueOrDefault("Value", string.Empty);
              var regExPattern = attributes.GetValueOrDefault("RegExPattern", string.Empty);
              if (string.IsNullOrEmpty(tokenName))
              {
            log.Warn(string.Format("No 'TokenName' was specified for {0}", name));
            return;
              }

              if (string.IsNullOrEmpty(value))
              {
            log.Warn(string.Format("No 'Value' was specified for {0}", name));
            return;
              }

              if (string.IsNullOrEmpty(regExPattern))
              {
            RepositoryInfoHub.Instance.AddToken(tokenName, () =>
              {
            log.DebugFormat("Setting custom replacement token {0} to [{1}]", tokenName, value);
            return value;
              });
              }
              else
              {
            var regex = new Regex(regExPattern, RegexOptions.Compiled);
            RepositoryInfoHub.Instance.AddToken(tokenName, () =>
              {
            var input = RepositoryInfoHub.Instance.ParseTokens(value);
            log.DebugFormat("Preparing custom replacement token {0}", tokenName);
            log.DebugFormat("Value: [{0}]", value);
            log.DebugFormat("Processses value: [{0}]", input);
            var match = regex.Match(input);
            if (match != null)
            {
              log.DebugFormat("RegEx group count: {0}", match.Groups.Count);
              if (match.Groups.Count > 1)
              {
                log.DebugFormat("Setting custom replacement token {0} to [{1}]", tokenName, match.Groups[1].Value);
                return match.Groups[1].Value;
              }
            }

            return string.Empty;
              });
              }
        }
开发者ID:BrightLight,项目名称:RepoCop,代码行数:51,代码来源:ReplacementTokenXmlHandler.cs

示例9: DoTryGetSourceControlInfo

        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!EnsureInternalSetup(solutionFullPath, ref properties))
                return false;

            var head_path = (string)properties.GetValueOrDefault("git:headPath", () => "");

            if (!File.Exists(head_path))
                return false;

            var head_content = File.ReadAllText(head_path);
            var branch_match = GitBranchRegex.Match(head_content);

            if (!branch_match.Success)
                return false;

            var branch_group = branch_match.Groups["branchName"];

            if (!branch_group.Success)
                return false;

            var branch_name = branch_group.Value;
            properties.Add("git:head", branch_name);

            properties.AddOrUpdate(KnownProperties.BranchName, branch_name);

            return true;
        }
开发者ID:gandarez,项目名称:VSCommands,代码行数:30,代码来源:GitSourceControlInfoProvider.cs

示例10: TestGetValueOrDefaultInexisting

 public void TestGetValueOrDefaultInexisting()
 {
     Dictionary<string, int> dictionary = new Dictionary<string, int>();
     dictionary["Dummy"] = 1;
     int result = dictionary.GetValueOrDefault("Dummy2");
     Assert.AreEqual(default(int), result);
 }
开发者ID:Finansnet,项目名称:UtilitiesKit,代码行数:7,代码来源:DictionrayExtensionTest.cs

示例11: GetValueOrDefault_NonEmptyDictionaryWithoutKey_ReturnsDefault

 public void GetValueOrDefault_NonEmptyDictionaryWithoutKey_ReturnsDefault()
 {
     IDictionary<object, object> dict = new Dictionary<object, object>
     {
         { "key", "value" }
     };
     object value = dict.GetValueOrDefault("anotherKey", "fallback");
     Assert.Equal("fallback", value);
 }
开发者ID:CodicePlastico,项目名称:Plastiline.Net,代码行数:9,代码来源:DictionaryExtensionTest.cs

示例12: LoadUserAuthInfo

        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
                tokens.UserId = authInfo.GetValueOrDefault("user_id");

            if (authInfo.ContainsKey("screen_name"))
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");

            try
            {
                if (tokens.UserId != null)
                {
                    var oauthToken = new OAuthAccessToken
                    {
                        OAuthProvider = this,
                        AccessToken = tokens.AccessToken,
                        AccessTokenSecret = tokens.AccessTokenSecret,
                    };
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(oauthToken, tokens.UserId);
                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        var obj = objs[0];
                        tokens.DisplayName = obj.Get("name");

                        string profileUrl;
                        if (obj.TryGetValue("profile_image_url", out profileUrl))
                            tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl;

                        if (SaveExtendedUserInfo)
                        {
                            obj.Each(x => authInfo[x.Key] = x.Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve twitter user info for '{userSession.TwitterUserId}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
开发者ID:AVee,项目名称:ServiceStack,代码行数:43,代码来源:TwitterAuthProvider.cs

示例13: GetValueOrDefault

 public void GetValueOrDefault()
 {
     #region GetValueOrDefault
     var dict = new Dictionary<string, int> () {
         { "a", 1 },
     };
     Assert.AreEqual (1, dict.GetValueOrDefault ("a"));
     Assert.AreEqual (0, dict.GetValueOrDefault ("c"));
     Assert.AreEqual (3, dict.GetValueOrDefault ("c", 3));
     #endregion
 }
开发者ID:rikkus,项目名称:cadenza,代码行数:11,代码来源:DictionaryCodaTest.cs

示例14: CreateInstruction

 protected override Instruction CreateInstruction(Dictionary<string, string> attributes)
 {
     var mailInstruction = new MailInstruction();
       mailInstruction.Body = attributes.GetValueOrDefault("Body", String.Empty);
       mailInstruction.BodyTemplateFile = attributes.GetValueOrDefault("BodyTemplateFile", String.Empty);
       mailInstruction.BccMailAddresses = attributes.GetValueOrDefault("BccMailAddresses", String.Empty);
       mailInstruction.CcMailAddresses = attributes.GetValueOrDefault("CcMailAddresses", String.Empty);
       mailInstruction.FromMailAddress = attributes.GetValueOrDefault("FromMailAddress", String.Empty);
       mailInstruction.ReplyToMailAddress = attributes.GetValueOrDefault("ReplyToMailAddress", String.Empty);
       mailInstruction.Subject = attributes.GetValueOrDefault("Subject", String.Empty);
       mailInstruction.ToMailAddresses = attributes.GetValueOrDefault("ToMailAddresses", String.Empty);
       return mailInstruction;
 }
开发者ID:BrightLight,项目名称:RepoCop,代码行数:13,代码来源:MailInstructionXmlHandler.cs

示例15: Parse

        public static CommandLineArgs Parse(string[] args)
        {
            var dictionary = new Dictionary<string, string>();

            foreach (var a in args)
            {
                var keyValue = a.Split('=');
                var key = keyValue[0].Trim().ToLowerInvariant();
                var value = keyValue[1].Trim();

                dictionary.Add(key, value);
            }

            return new CommandLineArgs
            {
                MarkdownPath = dictionary.GetValueOrDefault("-output", "output.md"),
                DllPath = dictionary.GetValueOrDefault("-input", "."),
                UrlStringFormat = dictionary.GetValueOrDefault("-urlformat", "https://msdn.microsoft.com/en-us/library/{0}.aspx")
            };
        }
开发者ID:craftworkgames,项目名称:DotNet2Markdown,代码行数:20,代码来源:CommandLineArgs.cs


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