foreachを使用したコードをLINQを使用するコードにしたいのですが、書き方が分かりません。
どのように記述すれば同等の事が出来るのでしょうか。
実現したい処理は、
文字列配列から郵便番号と住所の文字列が含まれる文字列を探しだしてDataクラスに設定する処理です。
c#
1Regex regex = new Regex(@"(〒\d{3}-\d{4})\t*([^\t]*)"); 2Data data = new Data(); 3 4//住所が記載されている行は1行もしくは0行 5string[] values = new string[] { "AA", " 〒111-1111 ◯◯県△△町 ", "BB" };
foreachを利用すると以下のようにして、実現できました。
c#
1foreach(string text in values ) 2{ 3 if(regex.IsMatch(text)) 4 { 5 data.PostCode = regex.Match(text).Groups[1].Value; //"〒111-1111" 6 data.Address = regex.Match(text).Groups[2].Value; //"◯◯県△△町" 7 } 8}
LINQを使って以下のコードだと
resultはnullではないですが、何も取得できていないらしく「IndexOutOfRangeException」が発生します。
c#
1var result = 2 values 3 .Where(v => regex.IsMatch(v)) 4 .Select(v => regex.Match(v).Groups) 5 .Where(g => g.Count != 0) 6 .Select(s => new { Postcode = s[1].Value, Address = s[2].Value }); 7 8if (result != null) 9{ 10 data.Postcode = result.ToArray()[0].Postcode; 11 data.Address = result.ToArray()[0].Address; 12}
let句を使用したのが以下のコードなのですが、
上記と同様に何も取得できていないらしく「IndexOutOfRangeException」が発生します。
c#
1var result = 2 from value in values 3 where regex.IsMatch(value ) 4 let g = regex.Match(value ).Groups 5 where g.Count != 0 6 select new { Postcode = g[1].Value, Address = g[2].Value }; 7 8if (result != null) 9{ 10 data.Postcode = result.ToArray()[0].Postcode; 11 data.Address = result.ToArray()[0].Address; 12}
以上、アドバイスよろしくお願いします。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/01/16 14:20