C#で以下のような処理を実装しようとしています。
処理内容
文字列の配列を持つリストに対して、ある文字列で検索をかけ、ヒットすれば、
ヒットした配列に対して要素を追加するというものです。
サンプルプログラムとしては、
C#
1 static void Main(string[] args) 2 { 3 int i; 4 int j; 5 6 string[] searchlist = new string[3] { "犬", "猫", "ゴリラ" }; 7 8 string[] item1 = new string[3] { "ワニ", "猫", "犬" }; 9 string[] item2 = new string[3] { "コアラ", "キリン", "猫" }; 10 11 List<string[]> list = new List<string[]>(); 12 13 list.Add(item1); 14 list.Add(item2); 15 16 foreach(var item in list) 17 { 18 for (i = 0; i < searchlist.Length; i++) 19 { 20 if (item.Contains(searchlist[i]) == true) 21 { 22 for (j = 0; j < searchlist.Length; j++) 23 { 24 if (item.Contains(searchlist[j]) == false) 25 { 26 //itemに要素を追加したい 27 string[] temp = item; 28 Array.Resize(ref temp, temp.Length + 1); 29 temp[temp.Length - 1] = searchlist[j]; 30 31 list.Remove(item); //foreachの中でlistを変わっているので例外が発生 32 list.Add(temp); 33 34 break; 35 } 36 } 37 } 38 } 39 } 40 } 41
listが持っている配列全てに対して検索を書けるために、foreachで処理をしていますが、
検索がヒットした際に、要素を追加する処理を入れると例外が発生しています。
例外の原因は理解しているのですが、他の方法が思いつかず、質問させて頂いている次第です。
ご教示の程よろしくお願い致します。
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/27 00:43 編集
2018/06/27 07:36 編集
2018/06/29 00:06