どうも、ちょげ(@chogetarou)です。
forループを使ってリスト(List)の奇数の数値を削除する方法を紹介します。
方法

forループを使ってリスト(List)の奇数の数値を削除するには、Remove()を使います。
まず、forでリストのインデックスをループします。
forのループ処理内で、「リストのループ変数のインデックスの要素を2で割った結果が0でない」を条件に分岐します。
分岐内で、リストからRemove()を呼び出し、Remove()の引数にリストのループ変数のインデックスの要素を指定します。
//ls=対象のリスト
for (int i = 0; i < ls.Count; i++) {
int item = ls[i];
if (item % 2 != 0) {
ls.Remove(item);
}
}
上記のforループは、Remove()を呼び出したリストから奇数の数値を削除します。
使用例
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> nums = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < nums.Count; i++) {
int item = nums[i];
if (item % 2 != 0) {
nums.Remove(item);
}
}
foreach (int item in nums) {
Console.WriteLine(item);
}
}
}
出力:
2
4
6
8
10
コメント