なるほど、こんな方法もあったか。
ということで、オレの拡張メソッドコレクションに追加させて頂く。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Example
- {
- public static class Ext
- {
- public static Dictionary<K, V> ToDicWith<K, V>(this K[] key, V[] val)
- {
- if (key.Length != val.Length)
- {
- throw new ArgumentException("Length of both arguments must be the same.");
- }
- var dic = new Dictionary<K, V>();
- key.Select( (k, i) =>
- new { Key = k, Value = val[i] } )
- .ToList()
- .ForEach( d => dic.Add(d.Key, d.Value) );
- return dic;
- }
- }
- public class Program
- {
- public static void Main(string[] args)
- {
- char[] num = "123456789".ToCharArray();
- char[] alp = "abcdefghi".ToCharArray();
- var dic = num.ToDicWith(alp);
- foreach (var d in dic)
- {
- Console.WriteLine(d);
- }
- }
- }
- }
- /*
- * Build:
- *
- * gmcs array2dic.cs
- *
- * Run:
- *
- * mono array2dic.exe
- *
- */
$ mono array2dic.exe [1, a] [2, b] [3, c] [4, d] [5, e] [6, f] [7, g] [8, h] [9, i]
1 件のコメント:
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)
に伴う修正を行いました。
コメントを投稿