2010年9月25日土曜日

2つの配列から「値のペア」を列挙する、について

メモ、on Mono 2.6.7


なるほど、こんな方法もあったか。

ということで、オレの拡張メソッドコレクションに追加させて頂く。
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace Example  
  6. {  
  7.   public static class Ext  
  8.   {  
  9.     public static Dictionary<K, V> ToDicWith<K, V>(this K[] key, V[] val)  
  10.     {  
  11.       if (key.Length != val.Length)  
  12.       {  
  13.         throw new ArgumentException("Length of both arguments must be the same.");  
  14.       }  
  15.   
  16.       var dic = new Dictionary<K, V>();  
  17.   
  18.       key.Select( (k, i) =>  
  19.         new { Key = k, Value = val[i] } )  
  20.         .ToList()  
  21.         .ForEach( d => dic.Add(d.Key, d.Value) );  
  22.   
  23.       return dic;  
  24.     }  
  25.   }  
  26.   
  27.   public class Program  
  28.   {  
  29.     public static void Main(string[] args)  
  30.     {  
  31.       char[] num = "123456789".ToCharArray();  
  32.       char[] alp = "abcdefghi".ToCharArray();  
  33.   
  34.       var dic = num.ToDicWith(alp);  
  35.   
  36.       foreach (var d in dic)  
  37.       {  
  38.         Console.WriteLine(d);  
  39.       }  
  40.     }  
  41.   }  
  42. }  
  43. /* 
  44.  * Build: 
  45.  * 
  46.  *   gmcs array2dic.cs 
  47.  * 
  48.  * Run: 
  49.  * 
  50.  *   mono array2dic.exe 
  51.  * 
  52.  */  
$ mono array2dic.exe
[1, a]
[2, b]
[3, c]
[4, d]
[5, e]
[6, f]
[7, g]
[8, h]
[9, i]

1 件のコメント:

sta さんのコメント...

Before:
public static Dictionary<T1, T2> ToDicWith<T1, T2>(this T1[] key, T2[] val)

After:
public static Dictionary<K, V> ToDicWith<K, V>(this K[] key, V[] val)

に伴う修正を行いました。

コメントを投稿