本文整理汇总了C#中System.Collections.Dictionary.GetValueOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.GetValueOrDefault方法的具体用法?C# Dictionary.GetValueOrDefault怎么用?C# Dictionary.GetValueOrDefault使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Collections.Dictionary
的用法示例。
在下文中一共展示了Dictionary.GetValueOrDefault方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: throws_formatexception_when_value_cannot_be_parsed
public void throws_formatexception_when_value_cannot_be_parsed()
{
var dictionary = new Dictionary<string, string> { { "ID", "abc123" } };
Expect(() => dictionary.GetValueOrDefault<int>("ID"), Throws.TypeOf<FormatException>());
}
示例2: throws_invalidcastexception_when_value_is_null_for_value_type
public void throws_invalidcastexception_when_value_is_null_for_value_type()
{
var dictionary = new Dictionary<string, string> { { "length", null } };
Expect(() => dictionary.GetValueOrDefault<int>("length"), Throws.TypeOf<InvalidCastException>());
}
示例3: does_not_throw_invalidcastexception_when_value_is_null_for_reference_type
public void does_not_throw_invalidcastexception_when_value_is_null_for_reference_type()
{
var dictionary = new Dictionary<string, string> { { "length", null } };
var value = dictionary.GetValueOrDefault<ApplicationException>("length");
Expect(value, Is.Null);
}
示例4: get_datetime_from_other_culture
public void get_datetime_from_other_culture()
{
var collection = new Dictionary<string, string> { { "startDate", "05/04/2012 00:00:00" } };
var value = collection.GetValueOrDefault<DateTime>("startDate");
Expect(value, Is.EqualTo(new DateTime(2012, 5, 4)));
}
示例5: throws_invalidcastexception_when_type_is_not_supported
public void throws_invalidcastexception_when_type_is_not_supported()
{
var dictionary = new Dictionary<string, string> { { "length", "1:10:10" } };
Expect(() => dictionary.GetValueOrDefault<TimeSpan>("length"), Throws.TypeOf<InvalidCastException>());
}
示例6: get_int
public void get_int()
{
var collection = new Dictionary<string, string> { { "appId", "123" } };
var value = collection.GetValueOrDefault<int>("appId");
Expect(value, Is.EqualTo(123));
}
示例7: get_decimal_from_other_culture
public void get_decimal_from_other_culture()
{
var collection = new Dictionary<string, string> { { "appId", "1.23" } };
var value = collection.GetValueOrDefault<decimal>("appId");
Expect(value, Is.EqualTo(1.23m));
}
示例8: InitializeNameMappings
private static Dictionary<string, string> InitializeNameMappings(ConfigNode nameMappingNode)
{
Contract.Assert(nameMappingNode != null, "No name mappings");
Contract.Assert(String.Compare(nameMappingNode.Name, "cryptoNameMapping", StringComparison.Ordinal) == 0, "Invalid name mapping root");
Dictionary<string, string> nameMappings = new Dictionary<string, string>();
Dictionary<string, string> typeAliases = new Dictionary<string, string>();
// find the cryptoClases element
foreach (ConfigNode node in nameMappingNode.Children)
{
if (String.Compare(node.Name, "cryptoClasses", StringComparison.Ordinal) == 0)
{
foreach(ConfigNode cryptoClass in node.Children)
{
if (String.Compare(cryptoClass.Name, "cryptoClass", StringComparison.Ordinal) == 0)
{
if (cryptoClass.Attributes.Count > 0)
{
DictionaryEntry attribute = (DictionaryEntry)cryptoClass.Attributes[0];
typeAliases.Add((string)attribute.Key, (string)attribute.Value);
}
}
}
}
else if(String.Compare(node.Name, "nameEntry", StringComparison.Ordinal) == 0)
{
string friendlyName = null;
string className = null;
foreach(DictionaryEntry attribute in node.Attributes)
{
if(String.Compare((string)attribute.Key, "name", StringComparison.Ordinal) == 0)
friendlyName = (string)attribute.Value;
else if(String.Compare((string)attribute.Key, "class", StringComparison.Ordinal) == 0)
className = (string)attribute.Value;
}
if (friendlyName != null && className != null)
{
string typeName = typeAliases.GetValueOrDefault(className);
if (typeName != null)
nameMappings.Add(friendlyName, typeName);
}
}
}
return nameMappings;
}
示例9: DisplayPreferences
public DisplayPreferences(string id, Folder folder)
{
this.Id = new Guid(id);
Folder = folder;
ArrayList list = new ArrayList();
foreach (ViewType v in Enum.GetValues(typeof(ViewType)))
list.Add(ViewTypeNames.GetName(v));
viewType.Options = list;
try
{
this.viewType.Chosen = folder.DisplayPreferences != null ? folder.DisplayPreferences.ViewType ?? Config.Instance.DefaultViewType.ToString() : Config.Instance.DefaultViewType.ToString();
}
catch (ArgumentException)
{
Logging.Logger.ReportError("Invalid view type stored for {0}. Setting to Poster.", folder.Name ?? folder.GetType().Name);
viewType.Chosen = Localization.LocalizedStrings.Instance.GetString("PosterDispPref");
}
//set our dynamic choice options
this.sortDict = folder.SortOrderOptions;
this.sortOrders.Options = sortDict.Keys.ToArray();
this.indexDict = folder.IndexByOptions;
this.indexBy.Options = folder.IndexByOptions.Keys.ToArray();
verticalScroll = new BooleanChoice {Value = folder.DisplayPreferences != null && folder.DisplayPreferences.ScrollDirection == ScrollDirection.Vertical};
useBanner = new BooleanChoice();
showLabels = new BooleanChoice();
useCoverflow = new BooleanChoice {Value = false};
useBackdrop = new BooleanChoice {Value = folder.DisplayPreferences != null ? folder.DisplayPreferences.ShowBackdrop : Config.Instance.ShowBackdrop};
if (folder.DisplayPreferences != null)
{
var width = folder.DisplayPreferences.PrimaryImageWidth > 0 ? folder.DisplayPreferences.PrimaryImageWidth : Config.Instance.DefaultPosterSize.Width;
var height = folder.DisplayPreferences.PrimaryImageHeight > 0 ? folder.DisplayPreferences.PrimaryImageHeight : Config.Instance.DefaultPosterSize.Height;
customParms = folder.DisplayPreferences.CustomPrefs ?? new Dictionary<string, string>();
thumbConstraint = new SizeRef(new Size(width, height));
useBanner.Value = (customParms.GetValueOrDefault("MBCUseBanner", "false") == "true");
showLabels.Value = (customParms.GetValueOrDefault("MBCShowLabels", "false") == "true");
try
{
if (Config.Instance.RememberIndexing) indexBy.Chosen = folder.DisplayPreferences.IndexBy;
}
catch
{
indexBy.Chosen = Localization.LocalizedStrings.Instance.GetString("NoneDispPref");
}
}
try
{
sortOrders.Chosen = folder.DisplayPreferences != null ? folder.DisplayPreferences.SortBy ?? "Name" : "Name";
}
catch (ArgumentException)
{
Logging.Logger.ReportError("Invalid sort by stored for {0}. Setting to Name.", folder.Name ?? folder.GetType().Name);
sortOrders.Chosen = Localization.LocalizedStrings.Instance.GetString("NameDispPref");
}
ListenForChanges();
}
示例10: InitializeNameMappings
private static Dictionary<string, string> InitializeNameMappings(ConfigNode nameMappingNode)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
foreach (ConfigNode node in nameMappingNode.Children)
{
if (string.Compare(node.Name, "cryptoClasses", StringComparison.Ordinal) == 0)
{
foreach (ConfigNode node2 in node.Children)
{
if ((string.Compare(node2.Name, "cryptoClass", StringComparison.Ordinal) == 0) && (node2.Attributes.Count > 0))
{
DictionaryEntry entry = node2.Attributes[0];
dictionary2.Add((string) entry.Key, (string) entry.Value);
}
}
}
else if (string.Compare(node.Name, "nameEntry", StringComparison.Ordinal) == 0)
{
string key = null;
string str2 = null;
foreach (DictionaryEntry entry2 in node.Attributes)
{
if (string.Compare((string) entry2.Key, "name", StringComparison.Ordinal) == 0)
{
key = (string) entry2.Value;
}
else if (string.Compare((string) entry2.Key, "class", StringComparison.Ordinal) == 0)
{
str2 = (string) entry2.Value;
}
}
if ((key != null) && (str2 != null))
{
string valueOrDefault = dictionary2.GetValueOrDefault(str2);
if (valueOrDefault != null)
{
dictionary.Add(key, valueOrDefault);
}
}
}
}
return dictionary;
}
示例11: GenerateGameEntries
public async Task<IList<Game.AiCar>> GenerateGameEntries(CancellationToken cancellation = default(CancellationToken)) {
if (IsBusy) {
await RebuildGridAsync();
if (cancellation.IsCancellationRequested) return null;
}
var opponentsNumber = OpponentsNumberLimited;
if (FilteredView.Count == 0 || opponentsNumber == 0) {
return new Game.AiCar[0];
}
var skins = new Dictionary<string, GoodShuffle<CarSkinObject>>();
foreach (var car in FilteredView.OfType<RaceGridEntry>().Where(x => x.CarSkin == null).Select(x => x.Car).Distinct()) {
await car.SkinsManager.EnsureLoadedAsync();
if (cancellation.IsCancellationRequested) return null;
skins[car.Id] = GoodShuffle.Get(car.EnabledOnlySkins);
}
NameNationality[] nameNationalities;
if (opponentsNumber == 7 && OptionNfsPorscheNames) {
nameNationalities = new[] {
new NameNationality { Name = "Dylan", Nationality = "Wales" },
new NameNationality { Name = "Parise", Nationality = "Italy" },
new NameNationality { Name = "Steele", Nationality = "United States" },
new NameNationality { Name = "Wingnut", Nationality = "England" },
new NameNationality { Name = "Leadfoot", Nationality = "Australia" },
new NameNationality { Name = "Amazon", Nationality = "United States" },
new NameNationality { Name = "Backlash", Nationality = "United States" }
};
} else if (DataProvider.Instance.NationalitiesAndNames.Any()) {
nameNationalities = GoodShuffle.Get(DataProvider.Instance.NationalitiesAndNamesList).Take(opponentsNumber).ToArray();
} else {
nameNationalities = null;
}
List<int> aiLevels;
if (AiLevelFixed) {
aiLevels = null;
} else {
var aiLevelsInner = from i in Enumerable.Range(0, opponentsNumber)
select AiLevelMin + (int)((opponentsNumber < 2 ? 1f : 1f - (float)i / (opponentsNumber - 1)) * (AiLevel - AiLevelMin));
if (AiLevelArrangeReverse) {
aiLevelsInner = aiLevelsInner.Reverse();
}
if (Equals(AiLevelArrangeRandom, 1d)) {
aiLevelsInner = GoodShuffle.Get(aiLevelsInner);
} else if (AiLevelArrangeRandom > 0d) {
aiLevelsInner = LimitedShuffle.Get(aiLevelsInner, AiLevelArrangeRandom);
}
aiLevels = aiLevelsInner.Take(opponentsNumber).ToList();
Logging.Debug("AI levels: " + aiLevels.Select(x => [email protected]"{x}%").JoinToString(@", "));
}
IEnumerable<RaceGridEntry> final;
if (Mode.CandidatesMode) {
var list = FilteredView.OfType<RaceGridEntry>().SelectMany(x => new[] { x }.Repeat(x.CandidatePriority)).ToList();
if (ShuffleCandidates) {
var shuffled = GoodShuffle.Get(list);
if (_playerCar != null) {
var same = list.FirstOrDefault(x => x.Car == _playerCar);
if (same != null) {
shuffled.IgnoreOnce(same);
}
}
final = shuffled.Take(OpponentsNumberLimited);
} else {
var skip = _playerCar;
final = LinqExtension.RangeFrom().Select(x => list.RandomElement()).Where(x => {
if (x.Car == skip) {
skip = null;
return false;
}
return true;
}).Take(OpponentsNumberLimited);
}
} else {
final = NonfilteredList.Where(x => !x.SpecialEntry);
}
if (_playerCar != null) {
skins.GetValueOrDefault(_playerCar.Id)?.IgnoreOnce(_playerCar.SelectedSkin);
}
var takenNames = new List<string>(OpponentsNumberLimited);
return final.Take(OpponentsNumberLimited).Select((entry, i) => {
var level = entry.AiLevel ?? aiLevels?[i] ?? 100;
var skin = entry.CarSkin;
if (skin == null) {
skin = skins.GetValueOrDefault(entry.Car.Id)?.Next;
}
//.........这里部分代码省略.........
示例12: get_null_string_with_default
public void get_null_string_with_default()
{
var collection = new Dictionary<string, string> { { "app id", null } };
var value = collection.GetValueOrDefault("app id", "a default value");
Expect(value, Is.Null);
}