どうも、ちょげ(@chogetarou)です。
List(リスト)の要素を条件で検索して削除する方法を紹介します。
方法

Listの要素を条件で検索して削除するには、RemoveAll()を使います。
まず、ListからRemoveAll()メソッドを呼び出します。
RemoveAll()メソッドの引数に、引数を1つ持つラムダ式を指定します。
そして、RemoveAll()メソッドの引数のラムダ式で条件式を返します。
list.RemoveAll(item => 条件式);
RemoveAll()メソッドは、ラムダ式の条件式で要素を検索して、条件式でTrueを返した要素を全て削除します。
使用例
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
list.RemoveAll(item => item % 2 == 0);
foreach (var i in list) {
Console.WriteLine(i);
}
}
}
コメント