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

リスト(List)のnullの要素を削除する方法は、2つあります。
RemoveAll()
ひとつは、RemoveAll()を使う方法です。
まず、リストからRemoveAll()を呼び出します。
そして、RemoveAll()の引数に、「引数 => 引数 == null」のラムダ式を指定します。
//myList=対象のリスト
myList.RemoveAll(item => item == null);
上記のRemoveAll()は、リストのnullの要素を全削除します。
使用例
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<string> nums = new List<string>() { "one", null, "two", null, null, "three", "four", "five", null };
nums.RemoveAll(item => item == null);
Console.WriteLine(String.Join(",", nums));
}
}
出力:
one,two,three,four,five
Where()
もうひとつは、Where()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
次に、リストからWhere()を呼び出します。
Where()の引数に、「引数 => 引数 != null」のラムダ式を指定します。
そして、Where()からToList()を呼び出します。
//myList=対象のリスト
List<T> result = myList.Where(item => item != null).ToList();
上記のWhere()とToList()は、リストのnullの要素を全削除した結果を返します。
使用例
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<string> nums = new List<string>() { "one", null, "two", null, null, "three", "four", "five", null };
List<string> result = nums.Where(item => item != null).ToList();
Console.WriteLine(String.Join(",", result));
}
}
出力:
one,two,three,four,five
まとめ
リスト(List)のnullの要素を削除する方法は、次の2つです。
- RemoveAll()を使う方法
myList.RemoveAll(item => item == null);
- Where()を使う方法
List<T> result = myList.Where(item => item != null).ToList();
コメント