My question is whether, due to the way that strings act like value types, that will end up duplicating the strings to hold in the dictionary?
Strings in C# are not value types, and they are most certainly do not act like ones.
C# strings are immutable, which makes them suitable for use as keys in associative containers. However, using strings as keys, or in any other capacity for that matter, does not result in cloning of their content.
You can verify that no cloning is going on by checking for reference equality of your dictionary keys to SomeStringProperty
of your source array. Each key in the dictionary will be present in the source array:
var data = new[] {
new Something {SomeIntProperty=1, SomeStringProperty="A"}
, new Something {SomeIntProperty=2, SomeStringProperty="A"}
, new Something {SomeIntProperty=3, SomeStringProperty="A"}
, new Something {SomeIntProperty=4, SomeStringProperty="A"}
, new Something {SomeIntProperty=5, SomeStringProperty="A"}
, new Something {SomeIntProperty=6, SomeStringProperty="B"}
, new Something {SomeIntProperty=7, SomeStringProperty="B"}
, new Something {SomeIntProperty=8, SomeStringProperty="C"}
, new Something {SomeIntProperty=9, SomeStringProperty="D"}
};
var dict = data.GroupBy(s => s.SomeStringProperty)
.ToDictionary(g => g.Key);
foreach (var key in dict.Keys) {
if (data.Any(s => ReferenceEquals(s.SomeStringProperty, key))) {
Console.WriteLine("Key '{0}' is present.", key);
} else {
Console.WriteLine("Key '{0}' is not present.", key);
}
}
The above code prints
Key 'A' is present.
Key 'B' is present.
Key 'C' is present.
Key 'D' is present.
Demo.