回答編集履歴

1

追記

2024/04/16 10:15

投稿

fana
fana

スコア11708

test CHANGED
@@ -72,3 +72,64 @@
72
72
  A1004
73
73
  A1006 - A1010
74
74
  ```
75
+
76
+ ---
77
+
78
+ [追記]
79
+ 質問文のコードをなるべく使うようにするなら,例えばこんな感じでどうでしょう?
80
+
81
+ ```C#
82
+ private void CheckSerial( List<string> list )
83
+ {
84
+ var GroupLastIndexes = new List<int>(); //←名称変更,要素をintに変更.ここに連番グループの末尾要素のindexを収集することを考える.
85
+ string number = "";
86
+
87
+ for (int i = 0; i <= list.Count(); i++)
88
+ {
89
+ if (i == list.Count() - 1)
90
+ {
91
+ break;
92
+ }
93
+
94
+ int first = int.Parse(list[i].Substring(1, 4));
95
+ int second = int.Parse(list[i + 1].Substring(1, 4));
96
+
97
+ if (first + 1 == second)
98
+ {
99
+
100
+ }
101
+ else
102
+ {
103
+ GroupLastIndexes.Add( i ); //← i をAddするように変更
104
+ }
105
+ }
106
+
107
+ if (GroupLastIndexes.Count() == 0)
108
+ {
109
+ string first = list.First();
110
+ string last = list.Last();
111
+
112
+ number = first + "~" + last;
113
+ }
114
+ else //elseの処理を追加
115
+ {
116
+ GroupLastIndexes.Add( list.Count()-1 );
117
+
118
+ int iGroupStart = 0;
119
+ foreach( int iGroupLast in GroupLastIndexes )
120
+ {
121
+ if( number.Any() )number += " , ";
122
+
123
+ if( iGroupStart == iGroupLast )
124
+ { number += list[iGroupStart]; }
125
+ else
126
+ { number += list[iGroupStart] + "~" + list[iGroupLast]; }
127
+
128
+ iGroupStart = iGroupLast+1;
129
+ }
130
+ }
131
+
132
+ //※確認用に number の表示を追加
133
+ Console.WriteLine( number );
134
+ }
135
+ ```