text
stringlengths
0
13.4k
This overload attempts to parse the input string against an array of formats. The input string must match at least
one format in order to be parsed.
DateTime.TryParseExact("11242015", new [] { "yyyy-MM-dd", "MMddyyyy" }, null, DateTimeStyles.None,
out parsedValue); // true
GoalKicker.com – .NET Framework Notes for Professionals
12
Chapter 4: Dictionaries
Section 4.1: Initializing a Dictionary with a Collection Initializer
// Translates to `dict.Add(1, "First")` etc.
var dict = new Dictionary<int, string>()
{
{ 1, "First" },
{ 2, "Second" },
{ 3, "Third" }
};
// Translates to `dict[1] = "First"` etc.
// Works in C# 6.0.
var dict = new Dictionary<int, string>()
{
[1] = "First",
[2] = "Second",
[3] = "Third"
};
Section 4.2: Adding to a Dictionary
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "First");
dict.Add(2, "Second");
// To safely add items (check to ensure item does not already exist - would throw)
if(!dict.ContainsKey(3))
{
dict.Add(3, "Third");
}
Alternatively they can be added/set via the an indexer. (An indexer internally looks like a property, having a get and
set, but takes a parameter of any type which is specified between the brackets) :
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "First";
dict[2] = "Second";
dict[3] = "Third";
Unlike the Add method which throws an exception, if a key is already contained in the dictionary, the indexer just
replaces the existing value.
For thread-safe dictionary use ConcurrentDictionary<TKey, TValue>:
var dict = new ConcurrentDictionary<int, string>();
dict.AddOrUpdate(1, "First", (oldKey, oldValue) => "First");
Section 4.3: Getting a value from a dictionary
Given this setup code:
var dict = new Dictionary<int, string>()
{
{ 1, "First" },
GoalKicker.com – .NET Framework Notes for Professionals
13
{ 2, "Second" },
{ 3, "Third" }
};
You may want to read the value for the entry with key 1. If key doesn't exist getting a value will throw
KeyNotFoundException, so you may want to first check for that with ContainsKey:
if (dict.ContainsKey(1))
Console.WriteLine(dict[1]);
This has one disadvantage: you will search through your dictionary twice (once to check for existence and one to
read the value). For a large dictionary this can impact performance. Fortunately both operations can be performed
together:
string value;
if (dict.TryGetValue(1, out value))
Console.WriteLine(value);
Section 4.4: Make a Dictionary<string, T> with Case-
Insensivitve keys
var MyDict = new Dictionary<string,T>(StringComparison.InvariantCultureIgnoreCase)