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: | Line 324: | ||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
===C# 1.0=== |
|||
⚫ | |||
<lang csharp>static class Program |
|||
{ |
|||
static void Main() |
|||
{ |
|||
⚫ | |||
string[] |
string[] keys = { "foo", "bar", "val" }; |
||
string[] |
string[] values = { "little", "miss", "muffet" }; |
||
//Some basic error checking |
|||
int arg_length = 0; |
|||
if ( arg_keys.Length == arg_values.Length ) { |
|||
arg_length = arg_keys.Length; |
|||
} |
|||
System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length."); |
|||
⚫ | |||
h.add( arg_keys[i], arg_values[i] ); |
|||
⚫ | |||
{ |
|||
h.Add(keys[i], values[i]); |
|||
} |
|||
} |
|||
}</lang> |
}</lang> |
||
<code>Hashtable.Add</code> throws an exception when a key already exists. |
|||
Alternate way of adding values |
|||
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 |
|||
<lang csharp>for( int i = 0; i < arg_length; i++ ){ |
|||
.Zip(values, (k, v) => (k, v)) |
|||
h[ arg_keys[i] ] = arg_values[i]; |
|||
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v); |
|||
} |
|||
}</lang> |
}</lang> |
||