Hash from two arrays: Difference between revisions
Content added Content deleted
Langurmonkey (talk | contribs) (added langur language example) |
(→{{header|C sharp}}: Cleaned up; added more modern version) |
||
Line 324:
=={{header|C sharp}}==
===C# 1.0===
<lang csharp>System.Collections.HashTable h = new System.Collections.HashTable();▼
<lang csharp>static class Program
{
static void Main()
{
▲
string[]
string[]
System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");
for( int i = 0; i < arg_length; i++ ){▼
{
h.Add(keys[i], values[i]);
}
}
}</lang>
<code>Hashtable.Add</code> throws an exception when a key already exists.
An alternative method to add entries is to use the indexer setter, which replaces the old value associated with a key, if any:
<lang csharp>h[keys[i]] = values[i];</lang>
===Modern===
Uses <code>System.Collections.Generic.Dictionary<TKey, TValue></code>, <code>Enumerable.ToDictionary</code> from LINQ, extension method syntax, and lambda expressions.
<code>Enumerable.Zip</code> truncates the longer of its arguments.
<lang csharp>using System.Linq;
static class Program
{
static void Main()
{
string[] keys = { "foo", "bar", "val" };
string[] values = { "little", "miss", "muffet" };
var h = keys
.Zip(values, (k, v) => (k, v))
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v);
}
}</lang>
|