前提・実現したいこと
前回の質問で、下記コードについて教わったのですが、
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4using System.Linq; 5 6public class LinqTest : MonoBehaviour 7{ 8 void Start () 9 { 10 var list = new List<string>(); 11 list.Add ( "AAA" ); 12 list.Add ( "BBB" ); 13 list.Add ( "CCC" ); 14 15 // (1) で、元のリストの値 x と、int型 i を持つ匿名型(のIEnumerable)に変換 16 // (2) で、i を Key、x を Value とする Dictionary に変換 17 var dictionary = list.Select((x, i) => new { x, i} ) // (1) 18 .ToDictionary(d => d.i, d => d.x); // (2) 19 20 // 確認用 21 foreach ( var item in dictionary ) 22 { 23 Debug.Log ( $"{item.Key}, {item.Value}" ); 24 } 25 } 26}
これに関して、下記のことは教わり理解、確認しました。
・xが要素で、iが要素番号。 ・.ToDictionaryでDictionaryが生成できる過程。 ・new { } は匿名型のクラス。 ・実際にエディタでオンマウスでxやiの型を確認。 ・list.Select((x, i) => new {x, i})で匿名クラスのIEnumerableに変換される。
ただ、実際にこのIEnumerableを出力して中身を確かめる処理をしたくなり、
コードを組んだのですが、それができませんでした。
また、list.Select((x) => new {x}))としたときの中身も出力して比較を試みたかったのですが、
同様にできませんでした。
ご教示お願いします。
試したこと
C#
1 var list = new List<string>(); 2 list.Add ( "AAA" ); 3 list.Add ( "BBB" ); 4 list.Add ( "CCC" ); 5 6 var en = list.Select((x, i) => new {x, i}); 7 8 Debug.Log(en); 9 //System.Linq.Enumerable+<CreateSelectIterator>c__Iterator11`2[System.String,<>__AnonType0`2[System.String,System.Int32]] 10 11 foreach(string s in en) 12 { 13 Debug.Log(s); 14 }
foreachでエラーが起きます。
エラーメッセージ。
Cannot convert type `anonymous type' to `string'
同様に、
C#
1var en = list.Select((x) => new {x});
にしても、下記エラーメッセージが出力されます。
エラーメッセージ。
Cannot convert type `anonymous type' to `string'
追記
dynamicというものがあるらしくて、試してみましたが、下記エラーが出てしまいました。
匿名クラスのIEnumerable型を生成するには、<>に何を指定すればよいのでしょうか?
var enにすると、IEnumerable型ではなくなります。
IEnumerable<dynamic> en = new[]{ new{x = "AAA", i = 0}, new {x ="BBB", i = 1}, new {x = "CCC", i = 2}}; Debug.Log(en); foreach(var s in en){ Debug.Log(s.x +","+s.i); }
Dynamic keyword requires `System.Runtime.CompilerServices.DynamicAttribute' to be defined. Are you missing System.Core.dll assembly reference?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/01/18 02:05
2019/01/18 03:12
退会済みユーザー
2019/01/18 08:01 編集
2019/01/18 10:52
退会済みユーザー
2019/01/18 14:09
2019/01/19 04:36 編集
退会済みユーザー
2019/01/19 12:16
2019/01/19 13:11
退会済みユーザー
2019/01/19 13:13